青岛IT培训的小编总结,数组
使用扩展运算符(…)拷贝数组。
// badconst len = items.length;const itemsCopy = [];let i;for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}// goodconst itemsCopy = […items];
使用Array.from方法,将类似数组的对象转为数组。
const foo = document.querySelectorAll(‘.foo’);const nodes = Array.from(foo);
函数
立即执行函数可以写成箭头函数的形式。
(() => { console.log(‘Welcome to the Internet.’);
})();
那些需要使用函数表达式的场合,尽量用箭头函数代替。因为这样更简洁,而且绑定了this.
// bad[1, 2, 3].map(function (x) { return x * x;
});// good[1, 2, 3].map((x) => { return x * x;
});// best[1, 2, 3].map(x => x * x);

箭头函数取代Function.prototype.bind,不应再用self/_this/that绑定 this.
// badconst self = this;const boundMethod = function(…params) { return method.apply(self, params);
}// acceptableconst boundMethod = method.bind(this);// bestconst boundMethod = (…params) => method.apply(this, params);
简单的、单行的、不会复用的函数,建议采用箭头函数。如果函数体较为复杂,行数较多,还是应该采用传统的函数写法。
所有配置项都应该集中在一个对象,放在最后一个参数,布尔值不可以直接作为参数。
// badfunction divide(a, b, option = false ) {
}// goodfunction divide(a, b, { option = false } = {}) {
}
不要在函数体内使用arguments变量,使用rest运算符(…)代替。因为rest运算符显式表明你想要获取参数,而且arguments是一个类似数组的对象,而rest运算符可以提供一个真正的数组。
// badfunction concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join(‘’);
}// goodfunction concatenateAll(…args) { return args.join(‘’);
}
使用默认值语法设置函数参数的默认值。
// badfunction handleThings(opts) {
opts = opts || {};
}// goodfunction handleThings(opts = {}) { // …}
以上就是青岛IT培训给大家做的内容详解,更多关于UI的学习,请继续关注青岛IT培训