如何遍历包含对象的数组并访问它们的属性 [英] How to loop through an array containing objects and access their properties

查看:21
本文介绍了如何遍历包含对象的数组并访问它们的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历数组中包含的对象并更改每个对象的属性.如果我这样做:

I want to cycle through the objects contained in an array and change the properties of each one. If I do this:

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j]);

}

控制台应该调出数组中的每个对象,对吗?但实际上它只显示第一个对象.如果我控制台在循环之外记录数组,所有对象都会出现,所以肯定还有更多.

The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.

无论如何,这是下一个问题.我如何使用循环访问,例如数组中的 Object1.x?

Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j.x]);

}

这将返回未定义".循环外的控制台日志再次告诉我对象都具有x"的值.如何在循环中访问这些属性?

This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?

我在其他地方被推荐为每个属性使用单独的数组,但我想确保我已经用尽了这条途径.

I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.

谢谢!

推荐答案

使用 forEach 它是一个内置的数组函数.Array.forEach():

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});

这篇关于如何遍历包含对象的数组并访问它们的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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