如何在JavaScript中访问“关联”数组的第一个键? [英] How do I access the first key of an ‘associative’ array in JavaScript?

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

问题描述

我有一个js'allociative'数组,

I have a js 'associative' array, with

array['serial_number'] = 'value'

serial_number和value是字符串。
,例如 array ['20910930923'] ='20101102'

serial_number and value are strings. e.g. array['20910930923'] = '20101102'

我按值排序,工作正常。
假设我回到对象'已排序';

I sorted it by value, works fine. Let's say I get back the object 'sorted';

现在我想访问'sorted'数组的第一个KEY。
我该怎么办?我不认为我需要迭代

Now I want to access the first KEY of the 'sorted' array. How do I do it? I can't think I need an iteration with

for (var i in sorted)

并在第一个之后停止......

and just stop after ther first one...

谢谢

编辑:只是为了澄清,我知道js不支持关联数组(这就是为什么我把它放在标题中的高位逗号中)。

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).

推荐答案

指定JavaScript对象属性没有订单,很多人希望它不同。如果您需要订购,请放弃任何使用对象的尝试并使用 Array 来代替存储名称 - 值对象:

JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:

var nameValues = [
    {name: '20910930923', value: '20101102'},
    {name: 'foo', value: 'bar'}
];

...或作为与现有对象一起使用的有序属性名称列表:

... or as an ordered list of property names to use with your existing object:

var obj = {
   '20910930923': '20101102',
   'foo': 'bar'
};

var orderedPropertyNames = ['20910930923', 'foo'];

这篇关于如何在JavaScript中访问“关联”数组的第一个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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