简体   繁体   English

您如何迭代JavaScript对象的属性(如数组)?

[英]How do you iterate over a JavaScript object's properties like an array?

I don't mean using a for loop using the keys. 我的意思不是使用键进行for循环。

For example if you had an array like: 例如,如果您有一个类似的数组:

var fruitArray = ["Apples", "Bananas", "Coconuts"],
    curFruit   = 0;

You could "iterate" over that using buttons, say you've got a prev/next button and all those buttons do is decrement/increment the curFruit index. 您可以使用按钮“迭代”该按钮,说您有一个上一个/下一个按钮,而所有这些按钮所做的就是减小/增加curFruit索引。

So if I'm on Bananas, I could get Apples using the prev button using: 因此,如果我使用香蕉,则可以使用prev按钮使用以下命令获取苹果:

fruitArray[0] // Apples

Where the index was at 1 for Bananas but the prev button drops the index by one. 香蕉的索引为1,但上一个按钮将索引降低1。

So with an unknown-length object, and not using a numbered-index, how could you do that? 因此,对于一个长度未知的对象,而不使用数字索引,您该怎么做?

Say it's like this: 说是这样的:

var fruitObject = {"Apples":"Red", "Bananas":"Yellow", "Coconuts":"Brown"};

I realize you could have set 0, 1, 2 and the fruit name, but just to show that you don't know what the object key/index might be. 我知道您可以设置0、1、2和水果名称,但是只是为了表明您不知道对象键/索引可能是什么。

So if I'm on Bananas using 所以如果我在香蕉上使用

fruitObject.Bananas // yellow

How could I get to Apples using the same decrement idea as the Array? 我该如何使用与Array相同的减量思想来获得苹果?

My question is not about the for in method 我的问题不是关于for in方法

I don't know why that's not clear, it was literally the first line in my question. 我不知道为什么不清楚,这实际上是我的问题的第一行。

I think I found a solution anyway though it might not be direct/the most effective way to do it where I'll create a temporary local "look up". 我想无论如何我都找到了一个解决方案,尽管它可能不是直接的/最有效的方法,但我将创建一个临时的本地“查找”。

To explain: 解释:

Here's an object 这是一个对象

var colorObject = {"red":"apple", "blue":"blueberries", "yellow":"banana"};

I don't want to use the for in method to go from left to right complete. 我不想使用for in方法从左到右完成。

I want to be able to start/keep a current position like I'm at "blue":"berries" and I can jump to "red":"apple" without knowing what "red":"apple" is 我希望能够像在"blue":"berries"一样开始/保持当前位置,并且可以跳到“ red”:“ apple”而无需知道"red":"apple"是什么

My current solution in mind is, yes, though ironically I would use the for in method but to create a look up array. 我目前的想法是,是的,尽管具有讽刺意味的是,我会使用for in方法,但会创建一个查找数组。

Something like 就像是

var tempArray = [];

for (var key in colorObject) {
  tempArray.push(key);
}

Then I can navigate the object starting from anywhere using the increment/decrement method. 然后,我可以使用递增/递减方法从任意位置导航对象。

tempArray[1] would return "blue" and I could go to "red" by doing tempArray[0] which is interpreted as tempArray[1]将返回“蓝色”,而我可以通过执行tempArray[0]转到“ red”来解释为

colorObject.blue // blueberries

Edit thanks to the editor for making my question more clear 编辑感谢编辑使我的问题更加清楚

I did poorly word it so that's on me. 我的措辞很差,所以就在我身上。

This is not possible. 这是不可能的。 JavaScript object properties do not have a defined order , so there is no concept of Y key comes after X key. JavaScript对象属性没有定义的顺序 ,因此在X键之后没有Y键的概念。

Excerpt from EnumerateObjectProperties section of ECMAScript 2017 Draft (ECMA-262) (emphasis added): ECMAScript 2017草案(ECMA-262)的EnumerateObjectProperties部分的节选 (强调):

The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below. 没有指定枚举属性的机制和顺序,但必须符合以下指定的规则。

If you were to iterate over the properties of your fruitObject object, "Bananas" may or may not come before "Coconuts" , this behavior simply is not defined by the specification. 如果要遍历fruitObject对象的属性, "Bananas"可能会出现在"Coconuts"之前,也可能不会出现,那么规范就没有定义这种行为。 There does not even appear to be a guarantee the properties will come back in the same order each time you iterate over the properties. 似乎并不能保证每次迭代属性时,属性都会以相同的顺序返回。

The only way to have a consistent order would be to have an array. 具有一致顺序的唯一方法是拥有一个数组。 Optionally, you could do this by creating an array of the properties via Object.keys . (可选)您可以通过Object.keys创建属性数组。

 var fruitObject = {"Apples":"Red", "Bananas":"Yellow", "Coconuts":"Brown"}; // Get the property keys in an ordered list: var fruitObjectKeys = Object.keys(fruitObject); // An array of properties with a consistent order: fruitObjectKeys.forEach(function(prop) { console.log(prop, '=', fruitObject[prop]); }); 

Note however that the JavaScript engine running the code will decide what the order of the resulting array of properties is if you do it this way. 但是请注意,如果您这样做,运行代码的JavaScript引擎将决定结果属性数组的顺序。

Objects don't have order, so you can't say that the first element of fruitObject is "Apples", the second is "Bananas" and the third is "Cocounts". 对象没有顺序,因此不能说fruitObject的第一个元素是“ Apples”,第二个是“ Bananas”,第三个是“ Cocounts”。

You could get the keys as an array with Object.keys() and then do something like 您可以使用Object.keys()将键作为数组获取,然后执行类似的操作

var keys=Object.keys(fruitObject);
fruitObject[keys[0]];

Remember that in JS it's the obj.key is the same than obj["key"] . 请记住,在JS中, obj.keyobj["key"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM