今天同事在 case 语句加了一个花括号{} ,我感到挺诧异的,问了他为什么要这么干?原来他是为了实现 case 语句的块级作用域,可以解决命名的苦恼,这是一个好的实践,值得推荐。
function foo(condition) {
switch (condition) {
case 1: {
let a = 1;
break
}
case 2: {
let a = 2
console.log(a)
break;
}
}
}
foo(2)
关于 NaN
console.log(isNaN(NaN))
// true
console.log(isNaN('A String'))
// true
console.log(isNaN(undefined))
// true
console.log(isNaN({}))
// true
console.log(Number.isNaN(NaN))
// true
console.log(Number.isNaN('A String'))
// false
console.log(Number.isNaN(undefined))
// false
console.log(Number.isNaN({})) // false
群里的小伙伴关于 NaN 分享了一道面试题,如果你对上述结果感到疑惑的话,我从 MDN web docs 摘取了一些段落应该能帮助理解。
The initial value of
NaN 是一个值,不能被覆盖改变NaNis Not-A-Number — the same as the value ofNumber.NaN. In modern browsers,NaNis a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.
However, do note the difference between
这 2 个方法的关键差异是 isNaN 检测值是不是 NaN 或者转化成 number 类型后是不是NaN;另一个则看当前的值是不是 NaNisNaN()andNumber.isNaN(): the former will returntrueif the value is currentlyNaN, or if it is going to beNaNafter it is coerced to a number, while the latter will returntrueonly if the value is currentlyNaN

《switch 的块级作用域》有一个想法