转载—— https://blog.csdn.net/wp7021/article/details/79045485
1、统计一个字符串出现最多的字母
<script>
let findMaxDuplicateChar = function(str){
if(str.lenght === 1){
return str;
}
var charObj = {};
for(let i=0, len=str.length; i<len; i++){
if(!charObj[str.charAt(i)]){
charObj[str.charAt(i)] = 1;
}else{
charObj[str.charAt(i)] += 1;
}
}
console.log(charObj);
let maxChar = '',maxVal = 1;
for(let k in charObj){
if(charObj[k] >= maxVal){
maxChar = k;
maxVal = charObj[k];
}
}
return maxChar;
}
</script>
2、排序算法
冒泡排序:依次比较大小,小的与大的进行位置交换
<script>
function bubbleSort(arr){
for(let i=0,len=arr.length; i<len-1; i++){
for(let j=0; j<len; j++){
if(arr[i]>arr[j]){
let item = arr[i];
arr[i] = arr[j];
arr[j] = item;
}
}
}
return arr
}
</script>
快速排序:算法参考某个元素的值,将小于它的值放到左数组中,将大于它的值放到有数组中,然后再进行递归操作,返回合并的数组就是已经排好序的数组了
<script>
function quickSort(arr) {
if(arr.length<=1){
return arr;
}
let leftArr = [],rightArr = [],val = arr[0];
for (let i = 1, len = arr.length; i < len; i++) {
if(arr[i] > val){
rightArr.push(arr[i])
}else{
leftArr.push(arr[i])
}
}
return [].concat(quickSort(leftArr),[val],quickSort(rightArr));
}
</script>
3、不借助临时变量,进行两个整数的交换
<script>
function swap(a,b) {
b = b - a; //a=2, b=6
a = a + b; //a=8 , b=6
b = a - b; //a= 8, b=2
return [a,b]
}
console.log(swap(2,8)) //[8,2]
</script>
4、找出输入数组的最大差值,如:输入[10,5,11,7,8,9], 输出:6
<script>
function getMaxProfit(arr) {
var len= arr.length;
if(len<=1){
return arr
}
arr.sort(function(a,b){
return a-b;
});
return arr[len-1] - arr[0]
}
</script>
或
<script>
function getMaxProfit(arr) {
let minVal = arr[0],maxVal = 0;
for (let i = 1, len = arr.length; i < len; i++) {
let currentVal = arr[i];
minVal = Math.min(currentVal,minVal);
let potentialVal = currentVal - minVal;
maxVal = Math.max(potentialVal,maxVal);
}
return maxVal;
}
</script>
5、随机生成指定长度的字符串
<script>
function getRandomStr(num) {
let str = "abcdefg1234567890higkmlopqrstuvwxyz";
let temp='',
i=0,
len = str.length;
for (i; i < num; i++) {
temp += str.charAt(Math.floor(Math.random()*len)) ;
}
return temp;
}
</script>
6、实现类似getElementsByclassName的功能
<script>
function queryClassName(node, name) {
var start = '(^|[\n\r\t\f])',
end = '([\n\r\t\f]|$)';
var arr = [],
regex = new RegExp(start + name + end),
elements = document.getElementsByTagName('*'),
length = element.length,
i = 0,
element;
while (i < length) {
element += elements[i];
if (regex.test(element.className)) {
arr.push(element)
}
i++;
}
return arr;
}
</script>
---------------------
原文:https://blog.csdn.net/wp7021/article/details/79045485