1.
[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]
知識點:
Array/Reduce
arr.reduce(callback[, initialValue])
reduce接受兩個參數(shù), 一個回調(diào), 一個初始值.
回調(diào)函數(shù)接受四個參數(shù) previousValue, currentValue, currentIndex, array
需要注意的是 If the array is empty and no initialValue was provided, TypeError would be thrown.
所以第二個表達式會報異常. 第一個表達式等價于 Math.pow(3, 2) => 9; Math.pow(9, 1) =>9
答案 an error
2.
var val = 'smtg';
console.log('Value is ' + (val === 'smtg') ? 'Something' : 'Nothing');
兩個知識點:
Operators/Operator_Precedence
Operators/Conditional_Operator
簡而言之 + 的優(yōu)先級 大于 ?
所以原題等價于 'Value is true' ? 'Somthing' : 'Nonthing' 而不是 'Value is' + (true ? 'Something' : 'Nonthing')
答案 'Something'
3.var END = Math.pow(2, 53);
var START = END - 100;
var count = 0;
for (var i = START; i <= END; i++) {
count++;
}
console.log(count);
一個知識點:
Infinity
在 JS 里, Math.pow(2, 53) == 9007199254740992 是可以表示的最大值. 最大值加一還是最大值. 所以循環(huán)不會停.
4.
var two? = 0.2
var one ? = 0.1
var eight = 0.8
var six ? = 0.6
[two - one == one, eight - six == two]
JavaScript的設(shè)計缺陷?浮點運算:0.1 + 0.2 != 0.3
IEEE 754標準中的浮點數(shù)并不能精確地表達小數(shù)
那什么時候精準, 什么時候不經(jīng)準呢? 筆者也不知道...
答案 [true, false]
5.
function showCase2(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('undefined');
break;
default:
console.log('Do not know!');
}
}
showCase2(String('A'));
解釋:
String(x) does not create an object but does return a string, i.e. typeof String(1) === "string"
還是剛才的知識點, 只不過 String 不僅是個構(gòu)造函數(shù) 直接調(diào)用返回一個字符串哦.
答案 'Case A'
6.
parseInt(3, 8)
parseInt(3, 2)
parseInt(3, 0)
第一個題講過了, 答案 3, NaN, 3
7.
var a = [0];
if ([0]) {
console.log(a == true);
} else {
console.log("wut");
}
JavaScript-Equality-Table
答案: false
8.
1 + - + + + - + 1
這里應(yīng)該是(倒著看)
1 + (a) ?=> 2
a = - (b) => 1
b = + (c) => -1
c = + (d) => -1
d = + (e) => -1
e = + (f) => -1
f = - (g) => -1
g = + 1 ? => 1
所以答案 2
9.
[1 < 2 < 3, 3 < 2 < 1]
這個題也還可以.
這個題會讓人誤以為是 2 > 1 && 2 < 3 其實不是的.
這個題等價于
1 < 2 => true;
true < 3 => ?1 < 3 => true;
3 < 2 => false;
false < 1 => 0 < 1 => true;
答案是 [true, true]
10.
3.toString()
3..toString()
3...toString()
這個題也挺逗, 我做對了 :) 答案是 error, '3', error
你如果換一個寫法就更費解了
var a = 3;
a.toString()
這個答案就是 '3';
為啥呢?
因為在 js 中 1.1, 1., .1 都是合法的數(shù)字. 那么在解析 3.toString 的時候這個 . 到底是屬于這個數(shù)字還是函數(shù)調(diào)用呢? 只能是數(shù)字,因為3.合法啊!