gpt4 book ai didi

javascript - 当使用数字索引分配数组值时,javascript 是否会在数字索引上调用 .toString?

转载 作者:行者123 更新时间:2023-11-28 19:55:28 25 4
gpt4 key购买 nike

我有一个长度为 0 的数组,并且出于某种原因我决定向它添加属性。我可以使用括号表示法将属性分配给数组,如下所示:

array['name'] = 'keith';

该属性(property)'name' : keith将被添加到数组的属性列表中。此外,就像对对象使用括号表示法一样,括号内的表达式首先被字符串化。因此,如果我说 array[undefined] = '42' (当然,没有人会这样做),则 undefined 会转换为字符串,我现在拥有另一个属性 'undefined' : 42 。 array.length 仍然是 0,因为非整数键(也称为索引)不计入长度。

现在,我有点困惑了。在“正常”对象上,如果我要这样做:myObject[10] = 10那么我会有一个具有属性 '10' : 10 的对象,属性名称 10 已被字符串化。那么按照我们刚才所做的,array['2'] = 'foo';应该添加属性 '2' : 'foo'到数组和 array[3] = 'bar';应该做同样的事情:成为数组的属性并且不计入长度。但是,当然,这两个语句只是将它们的值分配给数组中各自的索引。我不是在提示,因为这种行为更直观,我只是想知道我的逻辑在哪里让我误入歧途。我今天读完array[0] = 'cat';后才知道这一切。有效评估为 array[ (0).toString() ] = 'cat';

最佳答案

来自Mozilla Developer resources :

It's possible to quote the JavaScript array indexes as well (e.g., years["2"] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is for this reason that "2" and "02" would refer to two different slots on the years object and the following example could be true:

console.log(years["2"] != years["02"]);

基本上,如果您传递的是一个字符串(或 int,因为它将转换为字符串),它可能是一个整数(如“0”),它将引用该整数的索引。如果不是,它将向您正在创建的 Array 对象添加一个属性,并且不计算长度。

请注意,手动增加数组的长度不会创建新的空元素,尽管减少长度实际上会删除 数组末尾的相应元素。

对于可能需要密集数组(具有固定长度)的非常具体的应用程序,请查看 Typed Arrays .

<小时/>

查看此示例 ( jsFiddle ):

var test = new Array();
test[undefined] = 'undefined';
console.log(test);
console.log(test.length);

// This adds a property to the object 'test'
// Returns:
// [undefined: "undefined"]
// 0

test['string'] = 'string';
console.log(test);
console.log(test.length);

// This adds another property to the object 'test'
// Returns:
// [undefined: "undefined", string: "string"]
// 0

test['00'] = 'zero 00';
console.log(test);
console.log(test.length);

// This adds yet another property to the object 'test',
// since 00 is not explicitly an int.
// Returns:
// [undefined: "undefined", string: "string", 00: "zero 00"]
// 0

test['0'] = 'zero 0';
console.log(test);
console.log(test.length);

// This adds an element to the array 'test'
// Returns:
// ["zero 0", undefined: "undefined", string: "string", 00: "zero 00"]
// 1

test[0] = 'zero 0 int';
console.log(test);
console.log(test.length);

// This overrides the element at index 0 in the array 'test'
// Returns:
// ["zero 0 int", undefined: "undefined", string: "string", 00: "zero 00"]
// 1

关于javascript - 当使用数字索引分配数组值时,javascript 是否会在数字索引上调用 .toString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22655132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com