为什么在添加命名属性时数组会以这种方式运行? [英] Why do arrays behave this way when I add named properties?

查看:116
本文介绍了为什么在添加命名属性时数组会以这种方式运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在浏览器控制台中做了以下实验

I did following experiment in browsers console

  1. 我创建了一个新的 Array .
  2. "foo" 作为命名索引"name" 添加到 Array .
  3. 使用 push 方法将"bar" 添加到 Array .
  1. I created a new Array.
  2. Added "foo" to the Array as named index "name".
  3. Added "bar" to the Array using push method.

4&5是对 Array

4 & 5 are tests on the Array

1. var myArray = [];            // undefined
2. myArray["name"] = "foo";     // "foo"
3. myArray.push("bar");         // 1

4. myArray.join(", ");          // "bar"
5. myArray["name"];             // "foo"

我的问题(我不明白的地方)

My questions (what I didn't understand)

  • .push()返回 1 ,它是 Array 的长度,但它必须为2作为> Array 具有两个值"foo"&酒吧"

  • .push() returns 1 which is the length of the Array, but it must be 2 as the Array has two values "foo" & "bar"

测试4显示 Array 仅具有一个值"bar" ,但是测试5反对它显示其也具有值"foo".

Test 4 shows that the Array has only one value "bar" but test 5 oppose it showing that it also has a value "foo".

为什么 Array 方法( push join 等)不适用于键/值对?

Why doesn't Array methods (push, join etc) works on key/value pairs ?

推荐答案

.push()返回1,它是数组的长度,但必须为2,因为数组具有两个值"foo"&酒吧"

.push() returns 1 which is the length of the Array, but it must be 2 as the Array has two values "foo" & "bar"

否,因为JavaScript中的数组不是关联的数据结构(即使您可以将任意属性附加到它们).唯一被视为数组内容"的项目是那些属性名称满足某些条件的项目.

No, because arrays in JavaScript are not associative data structures (even though you can attach arbitrary properties to them). The only items that count as "array contents" are those whose property names satisfy certain conditions.

您还应该注意 length 可能如果阵列中有孔",则报告的数字也将大于预期值.例如:

You should also be aware that length may also report a number greater than what you expect if the array has "holes". For example:

var a = [1, 2, 3];
console.log(a.join(" "), a.length); // "1 2 3", 3
delete a[1];
console.log(a.join(" "), a.length); // "1  3", still 3!

测试4显示该数组只有一个值"bar",而测试5则相反,表明它也具有一个值"bar".

Test 4 shows that the Array has only one value "bar" but test 5 oppose it showing that it also has a value "bar".

这无关紧要.该数组还具有许多其他属性,但是 join 将只能触摸前面提到的那些.

That's irrelevant. The array also has many other properties, but join will only touch those mentioned earlier.

为什么Array方法(推,联接等)不适用于键/值对?

Why doesn't Array methods (push, join etc) works on key/value pairs ?

因为这就是规范所说的.

Because that's what the spec says.

然后关联数组如何工作以及我们如何处理它(方法,属性等).

Then how does associative Array works and how we can handle it(methods, properties etc).

如果要使用字符串键,请使用普通对象而不是数组.

Use a plain object instead of an array if you want string keys.

这篇关于为什么在添加命名属性时数组会以这种方式运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆