- 两个为真对象不相等
var x = [0];
if ([0]) {
console.log(x == true);
} else {
console.log("false");
}
// false 并非字符串的 “false”
- map方法遇到 "undefined" 时不做处理
var a = Array(3);
a[0] = 8;
a = a.map(function(elem) {
return "2";
})
console.log(a);
// [8, undefined × 2]
- 报错:Reduce of empty array with no initial value
[[3,2,1].reduce(Math.pow),[].reduce(Math.pow)]
// 报错:Reduce of empty array with no initial value
[3,2,1].reduce(Math.pow)
// 9
- delete length ?
function show() {}
delete show.length;
console.log(typeof show.length);
// number
- 函数表达式没有变量提升
(function() {
var x = foo();
var foo = function foo() {
return "bar"
};
console.log(x);
return x;
})();
// Uncaught TypeError: foo is not a function
- 连等赋值,a 为全局变量
(function() {
var b = a = 1;
})();
console.log(a);
console.log(b);
// a 输出 1;
// b 输出 Uncaught ReferenceError: b is not defined
- 对象操作和连等赋值
var a = {n:1};
var b = a; // 持有a,以回查
a.x = a = {n:2};
alert(a.x);// --> undefined
alert(b.x);// --> {n:2}
.运算优先于=赋值运算,因此此处赋值可理解为
1.声明a对象中的x属性,用于赋值,此时b指向a,同时拥有未赋值的x属性
2.对a对象赋值,此时变量名a改变指向到对象{n:2}
3.对步骤1中x属性,也即a原指向对象的x属性,也即b指向对象的x属性赋值
赋值结果:
a => {n: 2}
b => {n: 1, x: {n: 2 } }
javascript 连等赋值问题
var obj1 = { x: 5 };
var obj2 = obj1;
obj1.a = obj1 = { x: 6 };
console.log(obj1.a);
console.log(obj2.a);
// undefined
// {x: 6}
- 构造函数返回一个对象
x = {};
function bar() {
this.x = 2;
return x;
}
var foo = new bar();
console.log(foo.x);
// undefined
- 返回值之后的变量提升
function bar() {
return foo;
foo = 10;
function foo() {}
var foo = 11;
}
console.log(typeof bar())
// 'function'
- 作用域
var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
return this.x;
}
}
}
var go = foo.baz.bar;
console.log(go());
console.log(foo.baz.bar());
// 3
// 1
- 闭包
function fun1() {
var n = 167;
nAdd = function() {
n += 1;
}
function fun2() {
return n;
}
return fun2;
}
var result = fun1();
var a = result();
nAdd();
var b = result();
console.log(a);
console.log(b);
// 167
// 168
- return 之后
var foo = 1;
function bar() {
foo = 10;
return;
function foo() {}
}
bar();
console.log(foo);
// 1 foo = 10 已经失效
- arguments 修改值
function foo(a) {
arguments[0] = 2;
console.log(a);
}
foo(1);
// 2