ES6笔记

发布于 2018-04-12  301 次阅读


一:

使用扩展运算符(...)拷贝数组:

//
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// cool !
const itemsCopy = [...items];

二:

立即执行函数可以写成箭头函数的形式:

(() => {
  console.log('Welcome to the Internet.');
})();

尽量写箭头函数使你的代码看起来简洁优雅:

// low
[1, 2, 3].map(function (x) {
  return x * x;
});

// cool !
[1, 2, 3].map(x => x * x);

 

————————————————————————————

生成一个序号数组:

var arr = [];
for(var i = 0;i<10;i++){
    arr.push(i)
}

方法:

Array.apply(null, {length:5 }).map(f.call,Number)//[0, 1, 2, 3, 4],f可以是任何函数
Array.apply(null, { '0':1,length:5 }).map(f.call,Number)//[0, 1, 2, 3, 4],不管元素是什么都一样
Array.apply(null, {length:5 }).map(f.call,Boolean)//[false, true, true, true, true]
Array.apply(null, {length:5 }).map(f.call,String)//["0", "1", "2", "3", "4"]
Array.apply(null, {length:5 }).map(eval.call,Object)//[Number, Number, Number, Number, Number]

 

最后更新于 2018-04-12