15个常用JS优化代码技巧

1.用concat代替push,unshift,splice向数组中插入元素

 var arr = [1,2,3,4,5];
 //old method
 arr.unshift(0);
 //new method 快98%
 [0].concat(arr).concat([6]);
2. 面对大量的if-else语句,使用switch或封装成对象处理

//    用switch
switch(color) {
         case 'black':
             printBlackBackground();
             break;
         case 'red':
             printRedBackground();
             break;
         case 'blue':
             printBlueBackground();
             break;
         case 'green':
             printGreenBackground();
             break;
         default:
             printYellowBackground();
     }
	//封装成对象
     var colorObj = {
         'black': printBlackBackground,
         'red': printRedBackground,
         'blue': printBlueBackground,
         'green': printGreenBackground,
         'yellow': printYellowBackground
     };
     if (color in colorObj) {
       colorObj[color]();
     }

3.排列特殊数组用 sort(Intl.Collator().compare):

     ['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);
     // ["árbol", "cosas", "fútbol", "único"]
 
     ['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);
     // ["Wann", "wäre", "Woche", "wöchentlich"]


4.箭头函数

5. 检测子字符串是否存在于字符串或者变量是否存在于数组:更简单的使用indexOf实现contains功能
//正常情况:
var someText = 'javascript rules';
 if (someText.indexOf('javascript') !== -1) {
 }
 
 // or
 if (someText.indexOf('javascript') >= 0) {
 }
//更简单的:
var someText = 'text';
!!~someText.indexOf('tex'); // someText contains "tex" - true
!~someText.indexOf('tex'); // someText NOT contains "tex" - false
~someText.indexOf('asd'); // someText doesn't contain "asd" - false
~someText.indexOf('ext'); // someText contains "ext" - true

6. 更快的取整

一个位操作符 ~ 将输入的32位的数字(input)转换为 -(input+1). 两个位操作符将输入(input)转变为 -(-(input + 1)+1) 是一个使结果趋向于0的取整好工具. 对于数字, 负数就像使用Math.ceil()方法而正数就像使用Math.floor()方法. 转换失败时,返回0,这在Math.floor()方法转换失败返回NaN时或许会派上用场

// 单个 ~
 console.log(~1337)    // -1338
 
 // 数字输入
 console.log(~~47.11)  // -> 47
 console.log(~~-12.88) // -> -12
 console.log(~~1.9999) // -> 1
 console.log(~~3)      // -> 3
 
 // 转换失败
 console.log(~~[]) // -> 0
 console.log(~~NaN)  // -> 0
 console.log(~~null) // -> 0
 
 // 大于32位整数时转换失败
 console.log(~~(2147483647 + 1) === (2147483647 + 1)) // -> 0


7.更安全的字符串拼接:

//method 1
 var one = 1;
 var two = 2;
 var three = '3';
 var result = ''.concat(one, two, three); //"123"
 //method 2
 var one = 1;
 var two = 2;
 var three = '3';
 var result = one + two + three; //"33" instead of "123"

8. 为对象建立一个方法时,返回当前对象可以让你在一条链上调用方法

function Person(name) {
   this.name = name;
 
   this.sayName = function() {
     console.log("Hello my name is: ", this.name);
     return this;
   };
 
   this.changeName = function(name) {
     this.name = name;
     return this;
   };
 }
 
 var person = new Person("John");
 person.sayName().changeName("Timmy").sayName();

9. 转换为数字的更快方法:使用+(加号) 来实现

 var one = '1';
 var numberOne = +one; // Number 1
 var one = '1';
 var negativeNumberOne = -one; // Number -1


10.尽可能 使用 === 而不是 ==,避免隐式转换

11.过滤并排序字符串列表:

(1)如果不想改变我们的原始列表,使用filter(indexOf或者lastIndexOf)+sort;

const filteredAndSortedKeywords = keywords
  .filter((keyword, index) => keywords.lastIndexOf(keyword) === index)
   .sort((a, b) => a < b ? -1 : 1);
 console.log(filteredAndSortedKeywords);
 // ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']

(2)如果直接在原始列表上修改,使用indexOf+push+sort;

12.JS中的短路求值

(1)逻辑或可以用来给参数设置默认值

 function theSameOldFoo(name){
     name = name || 'Bar' ;
     console.log("My best friend's name is " + name);
 }
 theSameOldFoo();  // My best friend's name is Bar
 theSameOldFoo('Bhaskar');  // My best friend's name is Bhaskar

(2)逻辑与可以用来避免调用undefined参数的属性时报错

var dog = {
   bark: function(){
      console.log('Woof Woof');
    }
 };
 // 调用 dog.bark();
 dog.bark(); // Woof Woof.
 // 但是当dog未定义时,dog.bark() 将会抛出"Cannot read property 'bark' of undefined." 错误
 // 防止这种情况,我们可以使用 &&.
 dog&&dog.bark();   // This will only call dog.bark(), if dog is defined.
13.将类型更快速的转换为布尔值:  !!

!!"" // false
 !!0 // false
 !!null // false
 !!undefined // false
 !!NaN // false
 
 !!"hello" // true
 !!1 // true
 !!{} // true
 !![] // true

14. 避免修改和传递arguments给其他方法 — 影响优化

在JavaScript的方法里,arguments参数可以让你访问传递给该方法的所有参数。arguments是一个类数组对象;arguments可是使用数组标记访问,而且它有length参数,但是它没有filter, map, forEach这样内建到数组内的方法。因此,如下代码是一个非常常见的将arguments转换为数组的办法:

 var args = Array.prototype.slice.call(arguments);
 //或者
 var args = [].slice.call(arguments);
不幸的是,传递arguments给任何参数,将导致Chrome和Node中使用的V8引擎跳过对其的优化,这也将使性能相当慢。所以,正确的做法只有:
 var args = new Array(arguments.length);
     for(var i = 0; i < args.length; ++i) {
         args[i] = arguments[i];
     }
15.使用let声明解决闭包问题

//简单的闭包
for (var i=0; i<5; i++) {
    
        setTimeout(function(){
            console.log(i); 
        }, 1000); 
}
//用let解决闭包
for (let i=0; i<5; i++) {
    
        setTimeout(function(){
            console.log(i); 
        }, 1000); 
}


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值