44个 Javascript 变态题解析 (上)

本文解析了22道JavaScript面试题,覆盖了数组操作、类型判断、稀疏数组、浮点运算、函数作用域等核心概念,帮助读者深入理解JavaScript的工作原理。

第1题
[“1”, “2”, “3”].map(parseInt)
首先, map接受两个参数, 一个回调函数 callback, 一个回调函数的this值
其次, parseInt 只接受两个参数 string, radix(基数).

parseInt('1', 0);   //默认十进制
parseInt('2', 1);  //参数不合法
parseInt('3', 2);  //因为3在二进制中没有合法的数所以是NaN

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

第2题
[typeof null, null instanceof Object]
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上.
typeof 的结果请看下表:

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

所以答案 [object, false]

第3题
[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]
reduce接受两个参数, 一个回调, 一个初始值.
回调函数接受四个参数 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');
 "+" 的优先级 大于 "?"

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

声明变量提升

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 里, -2^53~2^53这个是极限值,i<=END,这个条件成立后再加上一还是END的值,所以会死循环,打印不出结果。

第7题

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

答案是 []

看一篇文章理解稀疏数组
译 JavaScript中的稀疏数组与密集数组
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;
  };
}

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

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

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

第8题

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

JavaScript的设计缺陷?浮点运算:0.1 + 0.2 != 0.3
答案 [true, false]

第9题

function showCase(value) {
    switch(value) {
    case 'A':
        console.log('Case A');
        break;
    case undefined:
        console.log('undefined');
        break;
    default:
        console.log('Do not know!');
    }
}
showCase(new String('A'));

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 undefined:
        console.log('undefined');
        break;
    default:
        console.log('Do not know!');
    }
}
showCase2(String('A'));

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 => 1
4 % 2 => 0
'13' % 2 => 1
-9 % % 2 => -1
Infinity % 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题

console.log([]==[])  //false
console.log([]=[])  //[]

第16题

'5' + 3 //js的字符串拼接53  parseInt("5")+parseInt(3) = 8
'5' - 3  //直接可以减去2

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

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

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

继续es6

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
bar(这里面的c和内部定义的c不是同一回事)结果是1+1+10=12

第20题

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

由于JavaScript实际上只有一种数字形式IEEE 754标准的64位双精度浮点数,其所能表示的整数范围为-2^53~2^53(包括边界值)。这里的111111111111111110000已经超过了2^53次方,所以会发生精度丢失的情况
答案 111111111111111110000

第21题

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

首先看Array.prototype.reverse方法,首先举几个栗子:

console.log(Array.prototype.reverse.call("skyinlayer"));
//skyinlayer
console.log(Array.prototype.reverse.call({}));
//Object {}
console.log(Array.prototype.reverse.call(123));
//123

这几个栗子可以得出一个结论,Array.prototype.reverse方法的返回值,就是this
Javascript中this有如下几种情况:
全局下this,指向window对象

console.log(this);
//输出结果:
//Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

函数调用,this指向全局window对象:

function somefun(){
    console.log(this);
}
somefun();
//输出结果:
//Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

方法调用,this指向拥有该方法的对象:

var someobj = {};
someobj.fun = function(){
    console.log(this);
};
console.log(someobj.fun());
//输出结果:
//Object {fun: function}

调用构造函数,构造函数内部的this指向新创建对象:

function Con() {
    console.log(this);
}
Con.prototype.somefun = function(){};
console.log(new Con());
//输出结果:
//Con {somefun: function}

显示确定this:

function somefun(){
    console.log(this);
};
somefun.apply("skyinlayer");
somefun.call("skyinlayer");
//输出结果:
//String {0: "s", 1: "k", 2: "y", 3: "i", 4: "n", 5: "l", 6: "a", 7: "y", 8: "e", 9: "r", length: 10}
//String {0: "s", 1: "k", 2: "y", 3: "i", 4: "n", 5: "l", 6: "a", 7: "y", 8: "e", 9: "r", length: 10} 

这里可以看到,使用的是函数调用方式,this指向的是全局对象window,所以答案是window

第22题

Number.MIN_VALUE > 0   //true
* Number.MAX_VALUE:最大的正数
* Number.MIN_VALUE:最小的正数
* Number.NaN:特殊值,用来表示这不是一个数
* Number.NEGATIVE_INFINITY:负无穷大
* Number.POSITIVE_INFINITY:正无穷大
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值