1.传入的参数数目不确定时(argument数目不确定,使用apply)
function log(){
console.log.apply(console, arguments);
};
log(1); //1
log(1,2); //1 2
如果改为console.log.call(console, arguments);
log(1,2); //[1, 2]
因为
2.复制类数组,并使其拥有数组的功能
function log(){
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
};
3.当字符串与变量结合时,使用模版字符串
const welcome = 'You have logged in as ' + first + ' ' + last + '.'
const db = 'http://' + host + ':' + port + '/' + database;
简写为:
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;
4.展开运算符(数组合并、浅复制)
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice( )
简写为:
const odd = [1, 3, 5];
const nums = [2, 4, 6, ...odd];
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
甚至在任何位置:
const odd = [1, 3, 5];
const nums = [2, 4, ...odd, 6];