Arra.prototpe.map() & null & undefined & delete

今天看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  {    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 : falsea1[0] === undefined : true---a2[0] === null : truea2[0] === undefined : false---a3[0] === null : falsea3[0] === undefined : true---a4[0] === null : falsea4[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);// falseconsole.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 propertiesa.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); // overridingextended.x  = undefined;console.log(extended.x); // undefineddelete 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

关键字:JavaScript

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部