Javascript 变态题解析系列四
2016-07-24 18:29:34
159
大家好,又在珠峰见面了,之前已经给大家演示了三期的变态面试题,最近面试的朋友很多,让我们继续用面试题打牢自己的基础,为自己的珠峰选择做更好的飞跃
第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]
只有 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']
因为函数的名字不可变.
第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