44個 JavaScript 變態(tài)題解析 (上)

原題來自:
http://javascript-puzzlers.herokuapp.com/

讀者可以先去做一下感受感受. 當(dāng)初筆者的成績是 21/44...

當(dāng)初筆者做這套題的時候不僅懷疑智商, 連人生都開始懷疑了....

不過, 對于基礎(chǔ)知識的理解是深入編程的前提. 讓我們一起來看看這些變態(tài)題到底變態(tài)不變態(tài)吧!

第1題

["1", "2", "3"].map(parseInt)

知識點:

Array/map

Number/parseInt

JavaScript parseInt

首先, map接受兩個參數(shù), 一個回調(diào)函數(shù) callback, 一個回調(diào)函數(shù)的this值

其中回調(diào)函數(shù)接受三個參數(shù) currentValue, index, arrary;

而題目中, map只傳入了回調(diào)函數(shù)--parseInt.

其次, parseInt 只接受兩個兩個參數(shù) string, radix(基數(shù)).

可選。表示要解析的數(shù)字的基數(shù)。該值介于 2 ~ 36 之間。
如果省略該參數(shù)或其值為 0,則數(shù)字將以 10 為基礎(chǔ)來解析。如果它以 “0x” 或 “0X” 開頭,將以 16 為基數(shù)。
如果該參數(shù)小于 2 或者大于 36,則 parseInt() 將返回 NaN。

所以本題即問

parseInt('1', 0);
parseInt('2', 1);
parseInt('3', 2);

首先后兩者參數(shù)不合法.

所以答案是 [1, NaN, NaN]

第2題

[typeof null, null instanceof Object]

兩個知識點:

Operators/typeof

Operators/instanceof

Operators/instanceof(中)

typeof 返回一個表示類型的字符串.

instanceof 運算符用來檢測 constructor.prototype 是否存在于參數(shù) object 的原型鏈上.

這個題可以直接看鏈接... 因為 typeof null === 'object' 自語言之初就是這樣....

typeof 的結(jié)果請看下表:

type result
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Symbol "symbol"
Host object Implementation-dependent
Function "function"
Object "object"

所以答案 [object, false]

第3題

[ [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

第4題

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'

第5題

var name = 'World!';
(function () {
if (typeof name === 'undefined') {
var name = 'Jack';
console.log('Goodbye ' + name);
} else {
console.log('Hello ' + name);
}
})();

這個相對簡單, 一個知識點:

Hoisting

在 JavaScript中, functions 和 variables 會被提升。變量提升是JavaScript將聲明移至作用域 scope (全局域或者當(dāng)前函數(shù)作用域) 頂部的行為。

這個題目相當(dāng)于

var name = 'World!';
(function () {
var name;
if (typeof name === 'undefined') {
name = 'Jack';
console.log('Goodbye ' + name);
} else {
console.log('Hello ' + name);
}
})();

所以答案是 'Goodbye Jack'

第6題

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中可以表示的最大整數(shù)不是2的53次方,而是1.7976931348623157e+308。

2的53次方不是js能表示的最大整數(shù)而應(yīng)該是能正確計算且不失精度的最大整數(shù),可以參見js權(quán)威指南。

9007199254740992 +1還是 9007199254740992 ,這就是因為精度問題,如果 9007199254740992 +11或者 9007199254740992 +111的話,值是會發(fā)生改變的,只是這時候計算的結(jié)果不是正確的值,就是因為精度丟失的問題。

第7題

var ary = [0,1,2];
ary[10] = 10;
ary.filter(function(x) { return x === undefined;});

答案是 []

看一篇文章理解稀疏數(shù)組

譯 JavaScript中的稀疏數(shù)組與密集數(shù)組

Array/filter

我們來看一下 Array.prototype.filter 的 polyfill:

if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/, thisArg/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) { // 注意這里!!!
var val = t[i];
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}

我們看到在迭代這個數(shù)組的時候, 首先檢查了這個索引值是不是數(shù)組的一個屬性, 那么我們測試一下.

0 in ary; => true
3 in ary; => false
10 in ary; => true

也就是說 從 3 - 9 都是沒有初始化的'坑'!, 這些索引并不存在與數(shù)組中. 在 array 的函數(shù)調(diào)用的時候是會跳過這些'坑'的.

第8題

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]

第9題

function showCase(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!');
}
}
showCase(new String('A'));

兩個知識點:

Statements/switch

String

switch 是嚴格比較, String 實例和 字符串不一樣.

var s_prim = 'foo';
var s_obj = new String(s_prim);
console.log(typeof s_prim); // "string"
console.log(typeof s_obj); // "object"
console.log(s_prim === s_obj); // false

答案是 'Do not know!'

第10題

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'

第11題

function isOdd(num) {
return num % 2 == 1;
}
function isEven(num) {
return num % 2 == 0;
}
function isSane(num) {
return isEven(num) || isOdd(num);
}
var values = [7, 4, '13', -9, Infinity];
values.map(isSane);

一個知識點

Arithmetic_Operators#Remainder

此題等價于

7 % 2 => 1
4 % 2 => 0
'13' % 2 => 1
-9 % % 2 => -1
Infinity % 2 => NaN

需要注意的是 余數(shù)的正負號隨第一個操作數(shù).

答案 [true, true, true, false, false]

第12題

parseInt(3, 8)
parseInt(3, 2)
parseInt(3, 0)

第一個題講過了, 答案 3, NaN, 3

第13題

Array.isArray( Array.prototype )

一個知識點:

Array/prototype

一個鮮為人知的實事: Array.prototype => [];

答案: true

第14題

var a = [0];
if ([0]) {
console.log(a == true);
} else {
console.log("wut");
}

JavaScript-Equality-Table

答案: false

第15題

[]==[]

== 是萬惡之源, 看上圖

答案是 false

第16題

'5' + 3
'5' - 3

兩個知識點:

Arithmetic_Operators#Addition

Arithmetic_Operators#Subtraction

  • 用來表示兩個數(shù)的和或者字符串拼接, -表示兩數(shù)之差.

請看例子, 體會區(qū)別:

'5' + 3
'53'
5 + '3'
'53'
5 - '3'
2
'5' - 3
2
'5' - '3'
2

也就是說 - 會盡可能的將兩個操作數(shù)變成數(shù)字, 而 + 如果兩邊不都是數(shù)字, 那么就是字符串拼接.

答案是 '53', 2

第17題

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

第18題

var ary = Array(3);
ary[0]=2
ary.map(function(elem) { return '1'; });

稀疏數(shù)組. 同第7題.

題目中的數(shù)組其實是一個長度為3, 但是沒有內(nèi)容的數(shù)組, array 上的操作會跳過這些未初始化的'坑'.

所以答案是 ["1", undefined × 2]

這里貼上 Array.prototype.map 的 polyfill.

Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
A = new Array(len);
k = 0;
while (k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
A[k] = mappedValue;
}
k++;
}
return A;
};

第19題

function sidEffecting(ary) {
ary[0] = ary[2];
}
function bar(a,b,c) {
c = 10
sidEffecting(arguments);
return a + b + c;
}
bar(1,1,1)

這是一個大坑, 尤其是涉及到 ES6語法的時候

知識點:

Functions/arguments

首先 The arguments object is an Array-like object corresponding to the arguments passed to a function.

也就是說 arguments 是一個 object, c 就是 arguments[2], 所以對于 c 的修改就是對 arguments[2] 的修改.

所以答案是 21.

然而!!!!!!

當(dāng)函數(shù)參數(shù)涉及到 any rest parameters, any default parameters or any destructured parameters 的時候, 這個 arguments 就不在是一個 mapped arguments object 了.....

請看:

function sidEffecting(ary) {
ary[0] = ary[2];
}
function bar(a,b,c=3) {
c = 10
sidEffecting(arguments);
return a + b + c;
}
bar(1,1,1)

答案是 12 !!!!

請讀者細細體會!!

第20題

var a = 111111111111111110000,
b = 1111;
a + b;

答案還是 111111111111111110000. 解釋是 Lack of precision for numbers in JavaScript affects both small and big numbers. 但是筆者不是很明白................ 請讀者賜教!

第21題

var x = [].reverse;
x();

這個題有意思!

知識點:

Array/reverse

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

也就是說 最后會返回這個調(diào)用者(this), 可是 x 執(zhí)行的時候是上下文是全局. 那么最后返回的是 window.

答案是 window

第22題

Number.MIN_VALUE > 0

true

今天先到這里, 下次我們來看后22個題!

本文來源:
https://github.com/xiaoyu2er/blog/issues/1?utm_source=ourjs.com
本文作者:xiaoyu2er
版權(quán)歸原作者所有,本文有改動。

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

推薦閱讀更多精彩內(nèi)容

  • 44 個 Javascript 變態(tài)題解析 (上)chrome://coba/content/container....
    清水蘆葦閱讀 349評論 0 0
  • 單例模式 適用場景:可能會在場景中使用到對象,但只有一個實例,加載時并不主動創(chuàng)建,需要時才創(chuàng)建 最常見的單例模式,...
    Obeing閱讀 2,109評論 1 10
  • 工廠模式類似于現(xiàn)實生活中的工廠可以產(chǎn)生大量相似的商品,去做同樣的事情,實現(xiàn)同樣的效果;這時候需要使用工廠模式。簡單...
    舟漁行舟閱讀 7,842評論 2 17
  • Javascript有很多數(shù)組的方法,有的人有W3C的API,還可以去MDN上去找,但是我覺得API上說的不全,M...
    頑皮的雪狐七七閱讀 4,219評論 0 6
  • “醒來了,就別再做夢” 我喜歡冬日里的暖陽 而你 是時光的傲寒 扯斷了夜夢里的影子 孤獨陪伴我一場冬眠
    飛行官小宇閱讀 325評論 1 0