Answer Analysis at the bottom
1, Q: What is the following code will print Why??
window.a || (window.a ='1');
console.log(window.a);
2, Q: What The following code will print Why??
var a = false + 1 ;
console.log(a);
3, Q: What is the following code will print Why??
var b = false === 1;
console.log(b);
4, Q: The following code will print what results Why??
if (typeof(a) && (-true) + (+undefined) + '') {
console.log('结果为真');
}else{
console.log('结果为假');
}
5, Q: The following code will print what results Why??
var a = !!'' + !!' ' - !!false + '1' || '结果为假';
console.log(a);
6, Q: The following code will print what results Why??
var fn = (
function fn1() {
return 1;
},
function fn2() {
return 2;
}
)();
console.log(fn);
7, Q: The following code will print what results Why??
var a = 10;
if (function b() {}) {
a += typeof b;
}
console.log(a);
8, Q: What is the result of the following few prints Why??
function fn() {
var marty = {
name: 'marty',
printName: function () {
console.log(this.name);
}
}
var test1 = {
name: 'test1'
}
var test2 = {
name: 'test2'
}
var test3 = {
name: 'test3'
}
test3.printName = marty.printName;
marty.printName.call(test1);// 1:
marty.printName.apply(test2);// 2:
marty.printName();// 3:
test3.printName();// 4:
}
fn();
9, Q: The following code will print what results Why??
var bar = {
a: '1'
}
function fn() {
bar.a = 'a';
Object.prototype.b = 'b';
return function () {
console.log(bar.a);
console.log(bar.b);
}
}
fn()();
-
1, the answer is:
“1”
Resolution:
原理在于小括号的优先级高于其他运算符, 所以先赋值 window.a='1' 然后在进行或运算。
-
2, the answer:
1
Resolution:
隐式类型转换 false 为 0 ,0 + 1 结果为1
-
3, the answer is:
false
Resolution:
隐式类型转换false 为 0
-
4, the answer is:
结果为真
Resolution:
typeof(a) 为 “undefined” ,隐式类型转换 (-true) 为 -1 ,(+undefined) 为 NaN 。-1 + NaN + '' = “NaN” , 所以结果为真
-
5. Answer:
“11”
Analysis:
隐式类型转换 !!'' 为 0 , !!' ' 字符串空格为 1 , !!false 为 0 , '1' , 1 + “1” =“11”
Note:对字符串和数字进行加法运算,数字转成字符串!
-
6. Answer:
2
Resolution:
逗号作为运算符使用, 结果为最后一个fn2() 。立即执行fn2()输出返回结果
-
7. Answer:
“10undefined”
Resolution:
(function b() {}) 是作为表达式使用,直接忽略掉函数名 。所以b 是一个未定义的状态
-
8, the answer is:
test1 test2 marty test3
Resolution:
这是一个this指向的问题:1、2 分别被 call()、apply() 改变了this的指向 3 、正常调用对象方法。4、将方法赋值给test3调用this指向test3
-
9, the answer is:
a b
Resolution:
这里形成了一个闭包 返回一个函数 , fn() 调用时修改bar.a的值。bar.b 在原型链上寻找到顶级Object.prototype的时候获得 b值