今天看Array.prototype.map()
在 MDN 的条目的时候发现
callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
写了以下代码来测试了一下
var a1 = new Array(1);
var a2 = [null];
var a3 = [undefined];
var a4 = [2];
delete a4[0];
var container = [a1,a2,a3,a4];
var container2 = new Array(4);
for (var i = 0, len = container2.length; i < len; i++) {
container2[i] = container[i].map( (val) => {
return 1;
});
console.log(container2[i]);
console.log("---");
}
得到以下输出
[ ]
---
[ 1 ]
---
[ 1 ]
---
[ ]
---
指定 null
也被认为数组的该 index
的元素被指定了值。Array.prototype.map()
的 callback
函数在这个元素未被赋值的时候,或者是被删除掉的时候不会被调用。
container.forEach((item, i) => {
var array = `a` + (i + 1);
console.log(`${array}[0] === null :`, item[0] === null);
console.log(`${array}[0] === undefined :`, item[0] === undefined);
console.log("---");
});
得到
a1[0] === null : false
a1[0] === undefined : true
---
a2[0] === null : true
a2[0] === undefined : false
---
a3[0] === null : false
a3[0] === undefined : true
---
a4[0] === null : false
a4[0] === undefined : true
---
为什么 a1 和 a3 的结果不一样,和 a4 又有什么联系呢?
var x = new Array(2)
vs var y = [undefined,undefined]
前者 Creates an array with undefined pointers.,var x = new Array(2)
就等于 var x = [ , ]
后者 creates an array with pointers to 3 undefined objects,也就是说,这些指针并不是 undefined
只是他们指向 undefined
其实 var u = undefined
也被认为是赋予了值
new Array(2)
创建一个长度为 2 的,但是没有 properties 的数组。[undefined,undefined]
返回一个长度为 2 的,有 2 个 properties 的数组(分别叫做 "0"
, "1"
的,值为 "undefined"
和 "undefined"
)
console.log( 0 in x);
// false
console.log( 0 in y);
// true
delete a.x
vs a.x = undefined
a = {
x: 'boo'
};
两种操作的结果是不同的,但是不能用===
来判断
两种操作都会得到
a.x === undefined
// true
应该使用:
// If you want inherited properties
'x' in a
// If you don't want inherited properties
a.hasOwnProperty('x')
delete
删除的是引用而不是 object 本身
http://stackoverflow.com/questions/742623/deleting-objects-in-javascript
从原型链上来说delete a.x
之后调用 a.x
会从原型链上寻找 x
a.x = undefined
之后不会,会直接返回 undefined
var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
extended.x = "overriding";
console.log(extended.x); // overriding
extended.x = undefined;
console.log(extended.x); // undefined
delete extended.x;
console.log(extended.x); // fromPrototype
delete
只会在 extended.hasOwnProperty("x"))
返回 true
的时候起作用,并且会使得 extended.hasOwnProperty("x"))
返回 false
。delete
不会影响原型链上的 properties
var obj = {x: "fromPrototype"};
var extended = Object.create(obj);
delete extended.x;
console.log(extended.x); // Still fromPrototype
参考:
delete a.x vs a.x = undefined
JavaScript “new Array(n)” and “Array.prototype.map” weirdness
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。