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.合法啊!

你可能感兴趣的:(Javascript 变态题解析)