Javascript 變態題解析

1.

[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]

知識點:

Array/Reduce

arr.reduce(callback[, initialValue])

reduce接受兩個參數, 一個回調, 一個初始值.

回調函數接受四個參數 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

簡而言之 + 的優先級 大于 ?

所以原題等價于 '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 是可以表示的最大值. 最大值加一還是最大值. 所以循環不會停.

4.

var two? = 0.2

var one ? = 0.1

var eight = 0.8

var six ? = 0.6

[two - one == one, eight - six == two]

JavaScript的設計缺陷?浮點運算:0.1 + 0.2 != 0.3

IEEE 754標準中的浮點數并不能精確地表達小數

那什么時候精準, 什么時候不經準呢? 筆者也不知道...

答案 [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 不僅是個構造函數 直接調用返回一個字符串哦.

答案 '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

這里應該是(倒著看)

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 都是合法的數字. 那么在解析 3.toString 的時候這個 . 到底是屬于這個數字還是函數調用呢? 只能是數字,因為3.合法啊!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容