数组既有关联关系又有索引关系吗? [英] Is array both associative and indexed?

查看:88
本文介绍了数组既有关联关系又有索引关系吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中的数组可以关联并建立索引吗?

Can an array in JavaScript be associative AND indexed?

我希望能够通过其位置或键值在数组中查找项目.

I'd like to be able to lookup an item in the array by its position or a key value.

推荐答案

JavaScript中没有诸如关联数组之类的东西.您可以使用对象文字,它们看起来像关联数组,但它们具有无序的属性.常规Javascript数组基于整数索引,并且不能关联.

There are no such things as associative arrays in Javascript. You can use object literals, which look like associative arrays, but they have unordered properties. Regular Javascript arrays are based on integer indexes, and can't be associative.

例如,使用此对象:

var params = {
    foo: 1,
    bar: 0,
    other: 2
};

您可以从对象访问属性,例如:

You can access properties from the object, for example:

params["foo"];

您还可以使用for...in语句遍历对象:

And you can also iterate over the object using the for...in statement:

for(var v in params) {
    //v is equal to the currently iterated property
}

但是,对属性迭代的顺序没有严格的规定-对象文字的两次迭代可能以不同的顺序返回属性.

However, there is no strict rule on the order of property iteration - two iterations of your object literal could return the properties in different orders.

这篇关于数组既有关联关系又有索引关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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