JavaScript 提升性能小技巧

1.惰性载入函数

function foo (){
    if(a!==b){
        console.log('aaa')
    }else{
        console.log('bbb')
    }
}



//优化后

function foo (){
    if(a!=b){
        foo = function(){
            console.log('aaa')
        }
    }else{
        foo = function(){
            console.log('bbb')
        }
    }
    return foo();
}

那么第一次运行之后就会覆写这个方法,下一次再运行的时候就不会执行判断了。当然现在只有一个判断,如果判断很多,分支比较复杂,那么节约的资源还是可观的。

2.一次性函数

var test = function(){

    console.log('msg')

    test = function(){
        console.log('foo')
    }

}


sca() // msg

sca()// foo

sca()// foo

跟上面的惰性载入函数同理,可以在函数体里覆写当前函数,那么可以创建一个一次性的函数,重新赋值之前的代码相当于只运行了一次,适用于运行一些只需要执行一次的初始化代码。

3.精确到指定位数的小数

const round =(n,decimals=0)=>Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);

round(1.356,2)//1.35

将数字四舍五入到指定的小数位数。使用 Math.round() 和模板字面量将数字四舍五入为指定的小数位数。省略第二个参数 decimals ,数字将被四舍五入到一个整数。

4.reduce方法同时实现map和filter

const num = [10,20,30,40];

const test = num.reduce((arr,item)=>{

    item = item*2;

    if(item>50){
        arr.push(item);
    }
    
    return arr;
},[]);

test;//[60,80]

假设现在有一个数列,你希望更新它的每一项(map的功能)然后筛选出一部分(filter的功能)。如果是先使用map然后filter的话,你需要遍历这个数组两次。

在下面的代码中,我们将数列中的值翻倍,然后挑选出那些大于50的数。

5.统计数组总相同项的个数

很多时候,你希望统计数组中重复出现项的个数然后用一个对象表示。那么你可以使用reduce方法处理这个数组。

下面的代码将统计每一种车的数目然后把总数用一个对象表示。

var cars = ['BMW','Benz','Benz','Tesla','BMW','Toyota'];
var carObj = cars.reduce( function ( obj,name) {

    obj[name] = obj[name]?++obj[name]:1;
    
    return obj;
},{});

carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }

6.接受函数返回多个结果

在下面的代码中,我们从/a中获取一个帖子,然后在/b中获取相关评论。由于我们使用的是async/await,函数把返回值放在一个数组中。而我们使用数组解构后就可以把返回值直接赋给相应的变量。

async function getFullPost (){

    return await new Promise.all([
        axios('/a'),
        axios('/b')
    ])

}

const [a,b] = getFullPost();

7.数组最大值

const a = [23,123,342,12];
const max = a.reduce(function(pre,cur,inde,arr){return pre>cur?pre:cur;}); // 342

8.字符串中字母出现的次数

const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';
const res = str.split('').reduce((accumulator, cur) => {accumulator[cur] ? accumulator[cur]++ : accumulator[cur] = 1; return accumulator;}, {});

9.数组去重

这个方法很多不一一列举了

var arr = [1,2,2,3,3,4,5];
//1
console.log([...new Set(arr)])

//2
console.log(Array.from(new Set(arr)))

//3
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);
发布了117 篇原创文章 · 获赞 446 · 访问量 62万+

猜你喜欢

转载自blog.csdn.net/zhuoganliwanjin/article/details/102541329