[英]javascript - array keys and fill
我发现js的以下行为有些奇怪,无法找出原因。
让我们假设以下代码:
var arrayName = new Array(15);
console.log(arrayName);
这将输出[undefined,undefined,undefined,...](未定义15次)。
现在,使用以下代码:
var arrayName = new Array(15).fill();
console.log(arrayName);
由于未提供任何用于填充的参数,因此将输出(按预期)[未定义,未定义,未定义... ...(未定义15次)。
现在让我们在数组中添加一个循环(使用for格式,而不是增量格式):
var arrayName = new Array(15);
console.log(arrayName);
for (var i in arrayName) {
console.log(i);
}
这将什么都不输出(不是我真正希望的原因-我希望数字从0到14)
现在让我们使用填充代码:
var arrayName = new Array(15).fill();
console.log(arrayName);
for (var i in arrayName) {
console.log(i);
}
这将输出0、1、2,...,14(两种情况下我都希望得到)。
那么...为什么有所不同?
我认为索引不是在第一种情况下创建的(但是仍然输出未定义的元素...为什么?)。 这是语言不一致还是背后的逻辑?
PS将鼠标移到空白框上可以查看内容。
基本上:不要在阵列上使用FOR.IN! : http : //ilikekillnerds.com/2015/02/stop-writing-slow-javascript/
for.in
是对象。 甚至MDN都声明了这一点: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
该数组已创建并且具有一些索引,但是由于没有任何实际数据(未定义),那么为什么会有任何键?
//The difference is in enumerable keys: console.log(Object.keys(new Array(15))); //Produces no keys since no data is allocated console.log(Object.keys(new Array(15).fill())); //Produces 15 keys //What you probably want is to loop through the allocated places in the array, not the keys of it: for(var i = 0; i < new Array(15).length; i++) { console.log(i) }
为什么是这样?
您是否尝试过Object.create
?
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/create
//Allocating a new object var test = Object.create({}, { p: { value: 42 } }); //Logging object... but where is p? console.log("where is p?",test); //there it is :) console.log("there it is",test.p); //Lets try that again test = Object.create({}, { p: { value: 42, enumerable: true } }); //Logging object... and there is p console.log("All good",test); //New object values are non-enumerable by default. Also on Arrays
var arrayName = new Array(15);
console.log(arrayName);
for (var i in arrayName) {
console.log(i);
}
让我们看看以上情况发生了什么。
var arrayName = new Array(15);
如果传递给Array构造函数的唯一参数是0到232 ^ -1(含)之间的整数,这将返回一个新的JavaScript数组,其长度设置为该数字。
这就是您在上述情况下所得到的。 因此,它是一个空数组,长度设置为15。现在,您在in循环中使用了它,它遍历了可枚举的属性,并且在每次迭代时将不同的属性名称分配给变量i
console.log(arrayName.propertyIsEnumerable('length'));
这将返回false,因此您没有可枚举属性的数组,并且它是一个空数组。 所以你什么也没得到。
现在,在第二种情况下,由于您使用了fill(),但是没有传递任何值作为第一个参数,该参数用于填充数组。 由于未传递任何值,因此整个数组都充满了未定义的值,并且定义了数组索引直到数组的长度。 (请参见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill此处的填充构造函数)
还要注意“数组索引只是具有整数名称的可枚举属性”。
现在,for in循环遍历数组的index属性,并打印它们的值,该值显示0-14。
要了解更多信息, 请访问https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.