时间: 2020-08-25|tag: 31次围观|0 条评论

44 个 JavaScript 变态题解析

第1题

["1", "2", "3"].map(parseInt)
  • map 接受两个参数,一个是回调函数 callback,一个是回调函数的 this 的值;其中回调函数接受三个参数 currentValue, index, arrary;
  • parseInt 只接受两个两个参数 string, radix(基数);
    • 可选。表示要解析的数字的基数。该值介于 2 ~ 36 之间;
    • 如果省略该参数或其值为 0,则数字将以 10 为基础来解析。如果它以 “0x” 或 “0X” 开头,将以 16 为基数;
    • 如果该参数小于 2 或者大于 36,则 parseInt() 将返回 NaN。

所以本题即问

parseInt('1', 0); // 1,默认为十进制parseInt('2', 1); // NaNparseInt('3', 2); // NaN

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

第2题

[typeof null, null instanceof Object]
  • typeof 的结果请看下表:
type         resultUndefined   "undefined"Null        "object"Boolean     "boolean"Number      "number"String      "string"Symbol      "symbol"Host object Implementation-dependentFunction    "function"Object      "object"
  • instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

在浏览器中,我们的脚本可能需要在多个窗口之间进行交互。多个窗口意味着多个全局环境,不同的全局环境拥有不同的全局对象,从而拥有不同的内置类型构造函数。这可能会引发一些问题。比如,表达式 [] instanceof window.frames[0].Array 会返回false,因为 Array.prototype !== window.frames[0].Array.prototype,并且数组从前者继承。

实际上你可以通过使用 Array.isArray(myObj) 或者Object.prototype.toString.call(myObj) === "[object Array]"来安全的检测传过来的对象是否是一个数组。

所以答案 [object, false]

第3题

[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]
  • arr.reduce(callback[, initialValue]);
  • reduce接受两个参数, 一个回调, 一个初始值;
  • 回调函数接受四个参数 previousValue, currentValue, currentIndex, array。

需要注意的是 If the array is empty and no initialValue was provided, TypeError would be thrown.

所以第二个表达式会报异常(TypeError: Reduce of empty array with no initial value)。第一个表达式等价于 Math.pow(3, 2) => 9; Math.pow(9, 1) =>9

答案 an error

第4题

var val = 'smtg';console.log('Value is ' + (val === 'smtg') ? 'Something' : 'Nothing');

简而言之 + 的优先级 大于 ?

所以原题等价于 '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);    }})();

在 JavaScript中, functions 和 variables 会被提升。变量提升是JavaScript将声明移至作用域 scope (全局域或者当前函数作用域) 顶部的行为。

这个题目相当于:

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);

在 JS 里, Math.pow(2, 53) == 9007199254740992 是可以表示的最大值。 最大值加一还是最大值,所以循环不会停。

第7题

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

答案是 []

我们来看一下 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;  };}

我们看到在迭代这个数组的时候, 首先检查了这个索引值是不是数组的一个属性, 那么我们测试一下.

0 in ary; => true3 in ary; => false10 in ary; => true

也就是说 从 3 - 9 都是没有初始化的'坑'!这些索引并不存在与数组中,在 array 的函数调用的时候是会跳过这些'坑'的。

第8题

var two   = 0.2var one   = 0.1var eight = 0.8var six   = 0.6[two - one == one, eight - six == two]

答案 [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'));

switch

switch (expression) {  case value1:    // 当 expression 的结果与 value1 匹配时,执行此处语句    [break;]  case value2:    // 当 expression 的结果与 value2 匹配时,执行此处语句    [break;]  ...  case valueN:    // 当 expression 的结果与 valueN 匹配时,执行此处语句    [break;]  [default:    // 如果 expression 与上面的 value 值都不匹配时,执行此处语句    [break;]]}
  • expression:一个用来与 case 子语句匹配的表达式。
  • case valueN:用于匹配 expression 的 case 子句。如果 expression 与给定的 valueN 相匹配,则执行该 case 子句中的语句直到该 switch 语句结束或遇到一个 break 。
  • default:一个 default 子句;如果给定,这条子句会在 expression 的值与任一 case 语句均不匹配时执行。

switch 是严格比较, 一个其表达式值与所输入的 expression 的值所相等的子句(使用 严格运算符,===)并将控制权转给该子句,执行相关语句。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 不仅是个构造函数,直接调用返回一个字符串。

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

此题等价于

// 需要注意的是余数的正负号随第一个操作数。7 % 2 => 14 % 2 => 0'13' % 2 => 1-9 % % 2 => -1Infinity % 2 => NaN

答案 [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 => []。

答案: true

第14题

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

答案: false

第15题

[]==[]

答案是 false

第16题

'5' + 3'5' - 3
  • 用来表示两个数的和或者字符串拼接, -表示两数之差。

答案是 '53', 2

第17题

1 + - + + + - + 1

答案 2

第18题

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

数组其实是一个长度为3, 但是没有内容的数组, array 上的操作会跳过这些未初始化的'坑'。

Array.prototype.map 的 polyfill:

if (!Array.prototype.map) {  Array.prototype.map = function(callback, thisArg) {    var T, A, k;    if (this == null) {      throw new TypeError(" this is null or not defined");    }    // 1. 将O赋值为调用map方法的数组.    var O = Object(this);    // 2.将len赋值为数组O的长度.    var len = O.length >>> 0;    // 3.如果callback不是函数,则抛出TypeError异常.    if (Object.prototype.toString.call(callback) != "[object Function]") {      throw new TypeError(callback + " is not a function");    }    // 4. 如果参数thisArg有值,则将T赋值为thisArg;否则T为undefined.    if (thisArg) {      T = thisArg;    }    // 5. 创建新数组A,长度为原数组O长度len    A = new Array(len);    // 6. 将k赋值为0    k = 0;    // 7. 当 k < len 时,执行循环.    while(k < len) {      var kValue, mappedValue;      //遍历O,k为原数组索引      if (k in O) {        //kValue为索引k对应的值.        kValue = O[ k ];        // 执行callback,this指向T,参数有三个.分别是kValue:值,k:索引,O:原数组.        mappedValue = callback.call(T, kValue, k, O);        // 返回值添加到新数组A中.        A[ k ] = mappedValue;      }      // k自增1      k++;    }    // 8. 返回新数组A    return A;  };      }

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

第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)

arguments 是一个 object, c 就是 arguments[2], 所以对于 c 的修改就是对 arguments[2] 的修改。

答案是 21

Arguments 对象

当函数参数涉及到 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

第21题

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

reverse 方法颠倒数组中元素的位置,并返回该数组的引用。

也就是说 最后会返回这个调用者(this), 可是 x 执行的时候是上下文是全局。 那么最后返回的是 window。

答案是 window

第22题

Number.MIN_VALUE > 0 // true

MIN_VALUE 属性是 JavaScript 中可表示的最小的数(接近 0 ,但不是负数)。它的近似值为 5 x 10-324。

第23题

[1 < 2 < 3, 3 < 2 < 1]

这个题等价于

 1 < 2 => true; true < 3 =>  1 < 3 => true; 3 < 2 => false; false < 1 => 0 < 1 => true;

答案是 [true, true]

第24题

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()

换一个写法:

var a = 3;a.toString()

这个答案就是 '3'

为啥呢?

因为在 js 中 1.1, 1., .1 都是合法的数字,那么在解析 3.toString 的时候这个 . 到底是属于这个数字还是函数调用呢? 只能是数字, 因为3.合法啊!

答案是 error, '3', error

第26题

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

y 被赋值到全局, x 是局部变量,所以打印 x 的时候会报 ReferenceError。

答案是 1, error

第27题

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

即使正则的字面量一致, 他们也不相等。

答案 false, false

第28题

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

字面量相等的数组也不相等。数组在比较大小的时候按照字典序比较。

答案 false, false, false, true

第29题

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

只有 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 是使用使用 new 创建的 f 实例的原型, 而 Object.getPrototypeOf 是 f 函数的原型。

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

答案 false

第31题

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

你不能更改函数的名称,此属性是只读的:

var object = {  // anonymous  someMethod: function() {}};object.someMethod.name = 'otherMethod';console.log(object.someMethod.name); // someMethod

要更改它,可以使用 Object.defineProperty()

答案 ['foo', 'foo']

第32题

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

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

第34题

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

这里 test 函数会将参数转为字符串, 'null', 'undefined' 自然都是全小写了。

答案: true, true

第35题

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

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

因为javascript 在定义数组的时候允许最后一个元素后跟一个, 所以这是个长度为三的稀疏数组。

答案: ", , "

第36题

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

因为是浏览器相关, class是个保留字(现在是个关键字了),自己在取属性名称的时候尽量避免保留字, 如果使用的话请加引号 a['class']。

第37题

var a = new Date("epoch")

简单来说, 如果调用 Date 的构造函数传入一个字符串的话需要符合规范, 即满足 Date.parse 的条件,另外需要注意的是: 如果格式错误 构造函数返回的仍是一个Date 的实例 Invalid Date。

答案 Invalid Date

第38题

var a = Function.length,    b = new Function().lengtha === 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 不传参数返回 Infinity, Math.max 不传参数返回 -Infinity。

答案: 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]

答案 [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()3b.getDay()6a.getMonth()2b.getMonth()3

答案 [false, false]

第43题

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

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

文章转载于:https://www.jianshu.com/p/5c3bde96b317

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《JavaScript Puzzlers!
   

还没有人抢沙发呢~