JavaScript数组如何具有非数字键? [英] How can JavaScript arrays have non-numeric keys?

查看:82
本文介绍了JavaScript数组如何具有非数字键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学到的是数组是一种对象。对象是具有键/值对的属性的集合。我一直认为数组是从0开始以数字索引的项目的集合。就在最近,我能够向数组添加非数字键。

What I have learned is an array is a type of object. Objects are a collection of properties with key/value pairs. I always thought arrays are a collection of items that are numerically indexed starting at 0. Just recently, I was able to add a non-numeric key to an array.

let arr = ['cribriform plate','mastoid','hyoid'];
arr.eyes = 'brown';
arr.skin = 'white';

这导致了

['cribriform plate','mastoid','hyoid',eyes : 'brown', skin : 'white'];

for ... in arr循环产生:

The for...in loop of arr yielded:

for(let i in arr){
    console.log(i);
    //0,1,2,3,eyes,skin
}

for ... of循环产生:

The for...of loop yielded:

for(let i of arr){
     console.log(i);
     //0,1,2,3
}

我能够使用for ... in循环遍历数组的所有键。但是,当我使用for ... of循环时,我只能对数字索引的键进行迭代。为什么?

I was able to iterate over all the keys of an array using the for...in loop. However, when I used the for...of loop, I was only able to iterate over the numerically indexed keys. Why is that?

而且,最精确的数组定义是什么?

And, what is the most accurate definition of an array?

推荐答案

使用 for..of 循环,将调用对象的 Symbol.iterator 属性。对于数组,这等效于数组的 .values()方法,该方法包含数组中每个索引的值。不包含非数字属性-数组通常不具有任意非数字属性,确实为数组分配任意非数字属性的代码可能需要重构。

With a for..of loop, the object's Symbol.iterator property is called. In the case of an array, this is equivalent to the array's .values() method, which contains the values for each index in the array. Non-numeric properties are not included - arrays generally don't have arbitrary non-numeric properties, and code that does assign arbitrary non-numeric properties to an array is likely in need of refactoring.

A for..in 循环迭代对象上的所有可枚举属性,包括从原型继承的属性。因此, for..of 在数组中将排除 for..in 的数组中的非数字属性。

A for..in loop iterates over all enumerable properties on an object, including those inherited from the prototype. Thus, for..of on an array will exclude non-numeric properties on an array that a for..in loop will include.

数组是对象,可以为其分配了任意属性,在大多数情况下,就像可以分配属性一样普通功能-这不是一个好主意。

Arrays, being objects, can have arbitrary properties assigned to them, for the most part, just like properties can be assigned to ordinary functions - it's just not a very good idea.

这篇关于JavaScript数组如何具有非数字键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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