Javascript小技巧

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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容