44個 JavaScript 變態題解析 (下)

承接上篇《44個 JavaScript 變態題解析 (上)

第23題

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

第24題

// the most classic wtf
2 == [[[2]]]

這個題我是猜的. 我猜的 true, 至于為什么.....

both objects get converted to strings and in both cases the resulting string is "2" 我不能信服...

第25題

3.toString()
3..toString()
3...toString()

這個題也挺逗, 我做對了 :) 答案是 error, '3', error

你如果換一個寫法就更費解了

var a = 3;
a.toString()

這個答案就是 '3';

為啥呢?

因為在 js 中 1.1, 1., .1 都是合法的數字. 那么在解析 3.toString 的時候這個 . 到底是屬于這個數字還是函數調用呢? 只能是數字, 因為3.合法啊!

第26題

(function(){
var x = y = 1;
})();
console.log(y);
console.log(x);

答案是 1, error

y 被賦值到全局. x 是局部變量. 所以打印 x 的時候會報 ReferenceError

第27題

var a = /123/,
b = /123/;
a == b
a === b

即使正則的字面量一致, 他們也不相等.

答案 false, false

第28題

var a = [1, 2, 3],
b = [1, 2, 3],
c = [1, 2, 4]
a == b
a === b
a > c
a < c

字面量相等的數組也不相等.

數組在比較大小的時候按照字典序比較

答案 false, false, false, true

第29題

var a = {}, b = Object.prototype;
[a.prototype === b, Object.getPrototypeOf(a) === b]

知識點:

Object/getPrototypeOf

只有 Function 擁有一個 prototype 的屬性. 所以 a.prototype 為 undefined.

而 Object.getPrototypeOf(obj) 返回一個具體對象的原型(該對象的內部[[prototype]]值)

答案 false, true

第30題

function f() {}
var a = f.prototype, b = Object.getPrototypeOf(f);
a === b

f.prototype is the object that will become the parent of any objects created with new f while Object.getPrototypeOf returns the parent in the inheritance hierarchy.

f.prototype 是使用使用 new 創建的 f 實例的原型. 而 Object.getPrototypeOf 是 f 函數的原型.

請看:

a === Object.getPrototypeOf(new f()) // true
b === Function.prototype // true

答案 false

第31題

function foo() { }
var oldName = foo.name;
foo.name = "bar";
[oldName, foo.name]

答案 ['foo', 'foo']

知識點:
Function/name

因為函數的名字不可變.

第32題

"1 2 3".replace(/\d/g, parseInt)

知識點:
String/replace#Specifying_a_function_as_a_parameter

str.replace(regexp|substr, newSubStr|function)

如果replace函數傳入的第二個參數是函數, 那么這個函數將接受如下參數

match 首先是匹配的字符串
p1, p2 .... 然后是正則的分組
offset match 匹配的index
string 整個字符串

由于題目中的正則沒有分組, 所以等價于問

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

答案: 1, NaN, 3

第33題

function f() {}
var parent = Object.getPrototypeOf(f);
f.name // ?
parent.name // ?
typeof eval(f.name) // ?
typeof eval(parent.name) // ?

先說以下答案 'f', 'Empty', 'function', error 這個答案并不重要.....

這里第一小問和第三小問很簡單不解釋了.

第二小問筆者在自己的瀏覽器測試的時候是 '', 第四問是 'undefined'

所以應該是平臺相關的. 這里明白 parent === Function.prototype 就好了.

第34題

var lowerCaseOnly = /^[a-z]+$/;
[lowerCaseOnly.test(null), lowerCaseOnly.test()]

知識點:

RegExp/test

這里 test 函數會將參數轉為字符串. 'nul', 'undefined' 自然都是全小寫了

答案: true, true

第35題

[,,,].join(", ")

[,,,] => [undefined × 3]

因為javascript 在定義數組的時候允許最后一個元素后跟一個,, 所以這是個長度為三的稀疏數組(這是長度為三, 并沒有 0, 1, 2三個屬性哦)

答案: ", , "

第36題

var a = {class: "Animal", name: 'Fido'};
a.class

這個題比較流氓.. 因為是瀏覽器相關, class是個保留字(現在是個關鍵字了)

所以答案不重要, 重要的是自己在取屬性名稱的時候盡量避免保留字. 如果使用的話請加引號 a['class']

第37題

var a = new Date("epoch")

知識點:

Date

Date/parse

簡單來說, 如果調用 Date 的構造函數傳入一個字符串的話需要符合規范, 即滿足 Date.parse 的條件.

另外需要注意的是 如果格式錯誤 構造函數返回的仍是一個Date 的實例 Invalid Date.

答案 Invalid Date

第38題

var a = Function.length,
b = new Function().length
a === b

我們知道一個function(Function 的實例)的 length 屬性就是函數簽名的參數個數, 所以 b.length == 0.

另外 Function.length 定義為1......

所以不相等.......答案 false

第39題

var a = Date(0);
var b = new Date(0);
var c = new Date();
[a === b, b === c, a === c]

還是關于Date 的題, 需要注意的是

如果不傳參數等價于當前時間.
如果是函數調用 返回一個字符串.

答案 false, false, false

第40題

var min = Math.min(), max = Math.max()
min < max

知識點:

Math/min

Math/max

有趣的是, Math.min 不傳參數返回 Infinity, Math.max 不傳參數返回 -Infinity :laughing:

答案: false

第41題

function captureOne(re, str) {
var match = re.exec(str);
return match && match[1];
}
var numRe = /num=(\d+)/ig,
wordRe = /word=(\w+)/i,
a1 = captureOne(numRe, "num=1"),
a2 = captureOne(wordRe, "word=1"),
a3 = captureOne(numRe, "NUM=2"),
a4 = captureOne(wordRe, "WORD=2");
[a1 === a2, a3 === a4]

知識點:

RegExp/exec

通俗的講

因為第一個正則有一個 g 選項 它會‘記憶’他所匹配的內容, 等匹配后他會從上次匹配的索引繼續, 而第二個正則不會

舉個例子

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}
// Found abb. Next match starts at 3
// Found ab. Next match starts at 9

所以 a1 = '1'; a2 = '1'; a3 = null; a4 = '2'

答案 [true, false]

第42題

var a = new Date("2014-03-19"),
b = new Date(2014, 03, 19);
[a.getDay() === b.getDay(), a.getMonth() === b.getMonth()]

這個....

JavaScript inherits 40 years old design from C: days are 1-indexed in C's struct tm, but months are 0 indexed. In addition to that, getDay returns the 0-indexed day of the week, to get the 1-indexed day of the month you have to use getDate, which doesn't return a Date object.

a.getDay()
3
b.getDay()
6
a.getMonth()
2
b.getMonth()
3

都是套路!

答案 [false, false]

第43題

if ('http://giftwrapped.com/picture.jpg'.match('.gif')) {
'a gif file'
} else {
'not a gif file'
}

知識點:

String/match

String.prototype.match 接受一個正則, 如果不是, 按照 new RegExp(obj) 轉化. 所以 . 并不會轉義
那么 /gif 就匹配了 /.gif/

答案: 'a gif file'

第44題

function foo(a) {
var a;
return a;
}
function bar(a) {
var a = 'bye';
return a;
}
[foo('hello'), bar('hello')]

在兩個函數里, a作為參數其實已經聲明了, 所以 var a; var a = 'bye' 其實就是 a; a ='bye'

所以答案 'hello', 'bye'

全部結束!

總結

由于筆者水平有限, 如果解釋有誤, 還望指出.

通過整理, 筆者發現絕大部分題目都是因為自己對于基礎知識或者說某個 API 的參數理解偏差才做錯的.

筆者的重災區在原型那一塊, 所以這次被虐和整理還是很有意義呀.

筆者相信 堅實的基礎是深入編程的前提. 所以基礎書還是要??窗?

最后這些變態題現在看看還變態嘛?

本文來源:https://github.com/xiaoyu2er/blog/issues/3
本文作者:xiaoyu2er
版權歸原作者所有,本文有改動。

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

推薦閱讀更多精彩內容