实用的 JavaScript 小技巧

3,296 阅读3分钟
原文链接: www.w3ctrain.com

数组插入

插入数据是家常便饭了,我们可以使用push插入到数组的后端,unshift插入到数组前端,也可以使用splice插入到中间。

然而有相应的方法并不意味着它们就是效率最优。

同样是插入数据,第二种效率高很多。

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

两种方法都修改了原始数组,不信? 瞧瞧这里 jsperf

插入到数组前端也一样,使用concat比unshift更高效。

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

值得一提的是,unshift修改了原来的数组,而concat返回一个新的数组 jsperf

使用splice在数组中间插入是最高效的做法了。

var items = ['one', 'two', 'three', 'four'];
items.splice(items.length / 2, 0, 'hello');

优化层叠的条件判断

如果你看到这堆条件判断代码,你会如何优化它?

if (color) {
  if (color === 'black') {
    printBlackBackground();
  } else if (color === 'red') {
    printRedBackground();
  } else if (color === 'blue') {
    printBlueBackground();
  } else if (color === 'green') {
    printGreenBackground();
  } else {
    printYellowBackground();
  }
  }

一种方式是使用switch,尽管这样能简介并且更有序,但不推荐这样做,因为会给debug增加麻烦:原因

switch(color) {
  case 'black':
    printBlackBackground();
    break;
  case 'red':
    printRedBackground();
    break;
  case 'blue':
    printBlueBackground();
    break;
  case 'green':
    printGreenBackground();
    break;
  default:
    printYellowBackground();
    }

尽可能的避免使用switch,那么最高效的做法就是通过一个object了。

var colorObj = {
  'black': printBlackBackground,
  'red': printRedBackground,
  'blue': printBlueBackground,
  'green': printGreenBackground,
  'yellow': printYellowBackground
  };
if (color && colorObj.hasOwnProperty(color)) {
  colorObj[color]();
  }

undefined,null的区别

  • undefined 表示一个变量没有被定义,或者定义了没有赋值。
  • null 是用来给变量赋值,表示”没有值”
  • JavaScript 会给一个没有初始化的变量赋予undefined
  • JavaScript 从不会将值赋为null,它是被程序员用来指定一个var 没有值。
  • undefined 在JSON中不合法,null合法
  • undefined 的 typeof 也是 undefined
  • null 的 typeof 是 object, 为什么
  • 它们都是原语
  • 都是 falsy (Boolean(undefined) // false, Boolean(null) // false)
  • 判断变量是否为undefined

    typeof variable === "undefined"
      
  • 判断变量是否为null

  • ‘==’为true, ‘===’为false

    null == undefined 
      null === undefined 
      

使用同一个方法处理数组和单一元素

与其拆分成两个方法来处理,不如写一个方法能同时处理两种情况(类似于jQuery的css方法)

你只需要先将它们并成一个数组,然后处理这个数据即可。

function printUpperCase(words) {
  var elements = [].concat(words);
  for (var i = 0; i < elements.length; i++) {
    console.log(elements[i].toUpperCase());
  }
  }

现在 printUpperCase 准备好了,调用吧。

printUpperCase("cactus");
printUpperCase(["cactus", "bear", "potato"]);

检查属性是否在对象上

任何继承自Object的对象都有in,hasOwnProperty两个方法,你知道它们的区别吗?

var myObject = {
  name: '@tips_js'
  };
myObject.hasOwnProperty('name'); 
'name' in myObject; 
myObject.hasOwnProperty('valueOf'); 
'valueOf' in myObject; 

只有属性是直接在对象上,hasOwnProperty 才会返回true,而 in 则是不三七二十一,把对象及其原型链都查找了一遍。

var myFunc = function() {
  this.name = '@tips_js';
  };
myFunc.prototype.age = '10 days';
var user = new myFunc();
user.hasOwnProperty('name'); 
user.hasOwnProperty('age'); 

Demo 看这里

声明提升

理解好声明提升将会帮助你组织好函数作用域。记住,变量声明和函数定义都会被提升。然而不管你是否在同一行声明定义了其他变量,变量定义都不会提升。变量声明是让操作系统知道这是个变量,而定义是给这个变量赋值。

function doTheThing() {
  console.log(notDeclared);
  console.log(definedLater);
  var definedLater;
  definedLater = 'I am defined!'
  console.log(definedLater)
  console.log(definedSimulateneously);
  var definedSimulateneously = 'I am defined!'
  console.log(definedSimulateneously)
  doSomethingElse();
  function doSomethingElse(){
    console.log('I did it!');
  }
  functionVar();
  var functionVar = function(){
    console.log('I did it!');
  }
  }

为了让代码可读性更高,尽量把你的变量在函数作用域顶部声明,使用之前要明确。

检测一小段javascript的效率

为了快速检测javascript代码块的执行效率,我们可以使用 console 方法,比如 console.time(label) 和 console.timeEnd(label)

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"); 

更多信息:Console Object Demo: jsfiddle

Node.js: 执行一个模块,如果它不是被required

在node中,你可以告知程序在require(‘./something.js’) 和 node something.js 时触发不同的代码。

if (!module.parent) {
    app.listen(8088, function() {
        console.log('app listening on port 8088');
    })
    } else {
    module.exports = app;
    }

查看文档了解更多。

本文的内容部分翻译自:github.com/loverajoel/…,一个分享js技巧的仓库,每日更新,感兴趣的自行关注。

如需转载,请注明出处: w3ctrain.com/2016/01/19/… ,欢迎加入前端Q群( 467969149 )