// bad
(function test() {
let a = b = c = 1; // 相当于 let a = (b = (c = 1));
})();
console.log(a); // throws ReferenceError
console.log(b); // 1
console.log(c); // 1
// good
(function test() {
let a = 1;
let b = a;
let c = a;
})();
console.log(a); // throws ReferenceError
console.log(b); // throws ReferenceError
console.log(c); // throws ReferenceError
本例的结果是 let 仅对 a 起到了预想效果,b 和 c 都成了全局变量, eslint: no-multi-assign
// bad
const num = new Number(0);
const str = new String('foo');
const bool = new Boolean(false);
console.log(typeof num, typeof str, typeof bool); // => object, object, object
if (num) { // true(对象相当于 true)
}
if (bool) { // true(对象相当于 true)
}
// good
const num = 0;
const str = 'foo';
const bool = false;
console.log(typeof num, typeof str, typeof bool); // => number, string, boolean
if (num) { // false(0 相当于 false)
}
if (bool) { // false
}
不要使用 new Number/String/Boolean。eslint: no-new-wrappers
使用 new Number/String//Boolean 声明不会有任何好处,还会导致变量成为 object 类型,可能引起 bug。