JS 优化技巧

392 阅读3分钟

向数组中插入元素

向一个数组中插入元素是平时很常见的一件事情。你可以使用push在数组尾部插入元素,可以用unshift在数组头部插入元素,也可以用splice在数组中间插入元素。

  var arr = [1,2,3,4,5];
  //old method
  arr.push(6);
  //new method
  arr[arr.length] = 6;
      

  var arr = [1,2,3,4,5];
  //old method
  arr.unshift(0);
  //new method
  [0].concat(arr);

优化嵌套的条件语句

面对大量的if-else语句:

//method1
     if (color) {
         if (color === 'black') {
             printBlackBackground();
         } else if (color === 'red') {
             printRedBackground();
         } else if (color === 'blue') {
             printBlueBackground();
         } else if (color === 'green') {
             printGreenBackground();
         } else {
             printYellowBackground();
         }
     }
     
 //method2
     switch(color) {
         case 'black':
             printBlackBackground();
             break;
         case 'red':
             printRedBackground();
             break;
         case 'blue':
             printBlueBackground();
             break;
         case 'green':
             printGreenBackground();
             break;
         default:
             printYellowBackground();
     }
     
 //method3
     switch(true) {
         case (typeof color === 'string' && color === 'black'):
             printBlackBackground();
             break;
         case (typeof color === 'string' && color === 'red'):
             printRedBackground();
             break;
         case (typeof color === 'string' && color === 'blue'):
             printBlueBackground();
             break;
         case (typeof color === 'string' && color === 'green'):
             printGreenBackground();
             break;
         case (typeof color === 'string' && color === 'yellow'):
             printYellowBackground();
             break;
     }
     
 //method4
     var colorObj = {
         'black': printBlackBackground,
         'red': printRedBackground,
         'blue': printBlueBackground,
         'green': printGreenBackground,
         'yellow': printYellowBackground
     };
     if (color in colorObj) {
       colorObj[color]();
     }

排列含音节字母的字符串

Javascript有一个原生方法sort可以排列数组。一次简单的array.sort()将每一个数组元素视为字符串并按照字母表排列。但是当你试图整理一个非ASCII元素的数组时,你可能会得到一个奇怪的结果。


['Shanghai', 'New York', 'Mumbai', 'Buenos Aires'].sort();
     // ["Buenos Aires", "Mumbai", "New York", "Shanghai"]
     
 //method1
     // 西班牙语
     ['único','árbol', 'cosas', 'fútbol'].sort();
     // ["cosas", "fútbol", "árbol", "único"] // bad order
     // 德语
     ['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();
     // ["Wann", "Woche", "wäre", "wöchentlich"] // bad order
 
 //method2
     ['ú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"]

undefined与null的区别

undefined表示一个变量没有被声明,或者被声明了但没有被赋值

null是一个表示“没有值”的值

Javascript将未赋值的变量默认值设为undefined

Javascript从来不会将变量设为null。它是用来让程序员表明某个用var声明的变量时没有值的。

undefined不是一个有效的JSON,而null是

undefined的类型(typeof)是undefined

null的类型(typeof)是object.

它们都是基本类型

null === undefined // false

检查某对象是否有某属性

//method1
     var myObject = {
       name: '@tips_js'
     };
     if (myObject.name) { }
 
 //method2
     var myObject = {
       name: '@tips_js'
     };
 
     myObject.hasOwnProperty('name'); // true
     'name' in myObject; // true
 
     myObject.hasOwnProperty('valueOf'); // false, valueOf 继承自原型链
     'valueOf' in myObject; // true

两者检查属性的深度不同,换言之hasOwnProperty只在本身有此属性时返回true,而in操作符不区分属性来自于本身或继承自原型链。

测量javascript代码块性能的小知识

快速的测量javascript的性能,我们可以使用console的方法,例如

  console.time("Array initialize");
  var arr = new Array(100),
      len = arr.length,
      i;
 
  for (i = 0; i < len; i++) {
      arr[i] = new Object();
  };
  console.timeEnd("Array initialize"); // 0.711ms

箭头函数

语法: 更少的代码行; 不再需要一遍一遍的打function了

语义: 从上下文中捕获this关键字

// 使用functions
var arr = [5,3,2,9,1];
var arrFunc = arr.map(function(x) {
  return x * x;
});
console.log(arrFunc )

// 使用箭头函数
var arr = [5,3,2,9,1];
var arrFunc = arr.map((x) => x*x);
console.log(arrFunc )

箭头函数在这种情况下省去了写小括号,function以及return的时间。

拼接变量

   //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"

拼接时使用加号,可能会导致意想不到的错误结果。

转换为数字的更快方法

将字符串转换为数字是极为常见的。最简单和快速的方法是使用+(加号) 来实现。

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