珠峰培训

Javascript 变态题解析系列三

作者:zhanglei

2016-07-17 09:06:45

151

大家好,又在珠峰见面了,之前已经给大家演示了两期的变态面试题,最近面试的朋友很多,让我们继续用面试题打牢自己的基础,为自己的珠峰选择做更好的飞跃

第17题

    
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

第18题

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

稀疏数组. 同第7题.

题目中的数组其实是一个长度为3, 但是没有内容的数组, 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语法的时候

首先 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.

然而!!!!!!

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

这个题有意思!

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

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

答案是 window

第22题

    
Number.MIN_VALUE > 0
    

true

第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" 我不能信服…

亲们,让我们下次继续各种变态的面试题。。。。