JavaScript Puzzlers javascript解惑
原文:/
Javascript环境: 浏览器标准 ECMA 262 (5.1)
运行结果可能跟node 或者jsc REPL中有所不同。 比如 this 和 global 在 firefox console, node repl 和jsc shell 是不一样的。
绿色部分是正确答案。
- 1.下面表达式的结果是?
["1", "2", "3"].map(parseInt)["1", "2", "3"][1, 2, 3][0, 1, 2]other what you actually get is[1, NaN, NaN]becauseparseInttakes two parameters (val, radix) andmappasses 3(element, index, array) - 2.下面表达式的结果是?
[typeof null, null instanceof Object]["object", false][null, false]["object", true]othertypeofwill always return "object" for native non callable objects. - 3.下面表达式的结果是?
[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]an error[9, 0][9, NaN][9, undefined] Per spec: reduce on an empty array without an initial value throwsTypeError - 4.下面表达式的结果是? (运算符优先级)
var val = 'smtg';console.log('Value is ' + (val === 'smtg') ? 'Something' : 'Nothing');Value is SomethingValue is NothingNaNother it actually prints 'Something' the+operator has higher precedence than the ternary one. - 5.下面表达式的结果是?
var name = 'World!';(function () { if (typeof name === 'undefined') { var name = 'Jack'; console.log('Goodbye ' + name); } else { console.log('Hello ' + name); }})();Goodbye JackHello JackHello undefinedHello World Thevardeclaration is hoisted to the function scope, but the initialization is not. - 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);0100101other it goes into an infinite loop, 2^53 is the highest possible number in javascript, and 2^53+1 gives 2^53, soican never become larger than that. - 7.下面表达式的结果是?
var ary = [0,1,2];ary[10] = 10;ary.filter(function(x) { return x === undefined;});[undefined × 7][0, 1, 2, 10][][undefined]Array.prototype.filteris not invoked for the missing elements. - 8.下面表达式的结果是?
var two = 0.2 var one = 0.1 var eight = 0.8 var six = 0.6[two - one == one, eight - six == two][true, true][false, false][true, false]other JavaScript does not have precision math, even though sometimes it works correctly. - 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'));Case ACase BDo not know!undefinedswitchuses===internally andnew String(x) !== x - 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'));Case ACase BDo not know!undefinedString(x)does not create an object but does return a string, i.e.typeof String(1) === "string" - 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);[true, true, true, true, true][true, true, true, true, false][true, true, true, false, false][true, true, false, false, false]Infinity % 2givesNaN,-9 % 2gives-1(modulo operator keeps sign so it's result is only reliable compared to 0) - 12.下面表达式的结果是?
parseInt(3, 8)parseInt(3, 2)parseInt(3, 0)3, 3, 33, 3, NaN3, NaN, NaNother3doesn't exist in base2, so obviously that's aNaN, but what about0?parseIntwill consider a bogus radix and assume you meant10, so it returns3. - 13.下面表达式的结果是?
Array.isArray( Array.prototype )truefalseerrorotherArray.prototypeis anArray. Go figure. - 14.下面表达式的结果是?
var a = [0];if ([0]) { console.log(a == true);} else { console.log("wut");}truefalse"wut"other[0]as a boolean is consideredtrue. Alas, when using it in the comparisons it gets converted in a different way and all goes to hell. - 15.下面表达式的结果是?
[]==[]truefalseerrorother==is the spawn of satan. - 16.下面表达式的结果是?
'5' + 3 '5' - 3"53", 28, 2errorother Strings know about+and will use it, but they are ignorant of-so in that case the strings get converted to numbers. - 17.下面表达式的结果是?
1 + - + + + - + 121errorother Great fun. - 18.下面表达式的结果是?
var ary = Array(3);ary[0]=2ary.map(function(elem) { return '1'; });[2, 1, 1]["1", "1", "1"][2, "1", "1"]other The result is["1", undefined × 2], asmapis only invoked for elements of theArraywhich have been initialized. - 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)312errorother The result is21, in javascript variables are tied to theargumentsobject so changing the variables changesargumentsand changing arguments changes the local variables even when they are not in the same scope. - 20.下面表达式的结果是???
var a = 111111111111111110000, b = 1111;a + b;111111111111111111111111111111111111110000NaNInfinity Lack of precision for numbers in JavaScript affects both small and big numbers. - 21.下面表达式的结果是?
var x = [].reverse;x();[]undefinederrorwindow[].reversewill returnthisand when invoked without an explicit receiver object it will default to the defaultthisAKAwindow - 22.下面表达式的结果是?
Number.MIN_VALUE > 0falsetrueerrorotherNumber.MIN_VALUEis the smallest value bigger than zero,-Number.MAX_VALUEgets you a reference to something like the most negative number. - 23.下面表达式的结果是???
[1 < 2 < 3, 3 < 2 < 1][true, true][true, false]errorother Implicit conversions at work. bothtrueandfalseare greater than any number. - 24.下面表达式的结果是?
2 == [[[2]]]truefalseundefinedother both objects get converted to strings and in both cases the resulting string is"2" - 25.下面表达式的结果是?
3.toString() 3..toString() 3...toString()"3", error, error"3", "3.0", errorerror, "3", errorother3.xis a valid syntax to define "3" with a mantissa ofx,toStringis not a valid number, but the empty string is. - 26.下面表达式的结果是?
(function(){ var x = y = 1;})();console.log(y);console.log(x);1, 1error, error1, errorotheryis an automatic global, not a function local one. - 27.下面表达式的结果是?
var a = /123/, b = /123/;a == ba === btrue, truetrue, falsefalse, falseother Per spec Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical. - 28.下面表达式的结果是?
var a = [1, 2, 3], b = [1, 2, 3], c = [1, 2, 4]a == ba === ba > ca < cfalse, false, false, truefalse, false, false, falsetrue, true, false, trueother Arrays are compared lexicographically with>and<, but not with==and=== - 29.下面表达式的结果是?
var a = {}, b = Object.prototype;[a.prototype === b, Object.getPrototypeOf(a) === b][false, true][true, true][false, false]other Functions have aprototypeproperty but other objects don't soa.prototypeisundefined. EveryObjectinstead has an internal property accessible viaObject.getPrototypeOf - 30.下面表达式的结果是?
function f() {}var a = f.prototype, b = Object.getPrototypeOf(f);a === btruefalsenullotherf.prototypeis the object that will become the parent of any objects created withnew fwhileObject.getPrototypeOfreturns the parent in the inheritance hierarchy. - 31.下面表达式的结果是?
function foo() { }var oldName = foo.name;foo.name = "bar";[oldName, foo.name]error["", ""]["foo", "foo"]["foo", "bar"]nameis a read only property. Why it doesn't throw an error when assigned, I do not know. - 32.下面表达式的结果是?
"1 2 3".replace(/\d/g, parseInt)"1 2 3""0 1 2""NaN 2 3""1 NaN 3"String.prototype.replaceinvokes the callback function with multiple arguments where the first is the match, then there is one argument for each capturing group, then there is the offset of the matched substring and finally the original string itself. soparseIntwill be invoked with arguments1, 0,2, 2,3, 4. - 33.下面表达式的结果是?
function f() {}var parent = Object.getPrototypeOf(f);f.name // ?parent.name // ?typeof eval(f.name) // ?typeof eval(parent.name) // ?"f", "Empty", "function", "function""f", undefined, "function", error"f", "Empty", "function", errorother The function prototype object is defined somewhere, has a name, can be invoked, but it's not in the current scope. - 34.下面表达式的结果是?
var lowerCaseOnly = /^[a-z]+$/;[lowerCaseOnly.test(null), lowerCaseOnly.test()][true, false]error[true, true][false, true] the argument is converted to a string with the abstractToStringoperation, so it is"null"and"undefined". - 35.下面表达式的结果是?
[,,,].join(", ")", , , ""undefined, undefined, undefined, undefined"", , """ JavaScript allows a trailing comma when defining arrays, so that turns out to be an array of three undefined. - 36.下面表达式的结果是?
var a = {class: "Animal", name: 'Fido'};a.class"Animal"Objectan errorother The answer is: it depends on the browser.classis a reserved word, but it is accepted as a property name by Chrome, Firefox and Opera. It will fail in IE. On the other hand, everybody will accept most other reserved words (int,private,throwsetc) as variable names too, whileclassis verboten.


发布评论