ChatGPT解决这个技术问题 Extra ChatGPT

如何遍历包含对象的数组并访问它们的属性

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

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

console.log(myArray[j]);

}

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

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

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

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

}

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

有人建议我在其他地方为每个属性使用单独的数组,但我想确保我首先用尽了这条途径。

谢谢!

您可以发布您的阵列样本吗?第一个代码片段似乎是正确的。
j 是一个数字。您在循环的顶部定义了它。
也许 myArray 毕竟不只是一个数组?
我们需要更多关于 myArray 是如何构造的信息
this answer 中指出了导致原始问题第二部分问题的简单语法错误(myArray[j.x] 应该是 myArray[j].x)。如果语法正确,常规的 for 循环就可以正常工作。

L
Lawrence Cherone

使用 forEach 它的内置数组函数。 Array.forEach()

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

@DoryZidon:forEach 不支持中断或停止 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
请注意,您确实拥有一个数组,这一点很重要。如果您从类似 document.getElementsByClassName 的东西中获得 yourArray,那将是一个 HTMLCollection,而不是一个数组。那么 this question 可能会有所帮助。
注意:forEach 是阻塞的,不支持 awaitfor...of 循环会。
救生员;谢谢@DoryZidon
Y
Yuci

在 JavaScript 中以函数式编程方式循环数组的一些用例:

1. 遍历一个数组

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

注意: Array.prototype.forEach() 严格来说不是函数方式,因为它作为输入参数的函数不应该返回值,因此不能被视为纯函数。

2.检查数组中的任何元素是否通过测试

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3.转换为新数组

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

注意: map() 方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

4. 总结一个特定的属性,并计算它的平均值

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5.在原有的基础上新建一个数组,但不修改

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6.统计每个类别的数量

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. 根据特定标准检索数组的子集

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

注意: filter() 方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。

8. 对数组进行排序

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

https://i.stack.imgur.com/HDP2k.png

9. 在数组中查找元素

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

https://i.stack.imgur.com/RjfY9.png

Array.prototype.find() 方法返回数组中满足提供的测试函数的第一个元素的值。

参考

Array.prototype.some()

Array.prototype.forEach()

Array.prototype.map()

Array.prototype.filter()

Array.prototype.sort()

传播语法

Array.prototype.find()


这是一个很棒的参考 - 这是这个问题的原创还是你在其他地方有类似的东西?
很好的解释和彻底的答案,感谢您的贡献。
你好,如果我想显示所有的名字然后做比较,你知道怎么做吗?
@dipgirl,是不是像下面这样? const people = [ {name: "john", age:23}, {name: "john", age:43}, {name: "jim", age:101}, {name: "bob", age:67} ]; const sortByAge = people.map(p => { console.log(p.name) return p }).sort(function (p1, p2) { return p1.age - p2.age; }); console.log(sortByAge);
所有用例都有简单的例子!我已经在浏览器中添加了书签!我的第一个 StackOverflow 书签 :-)
D
Dwayne Charrington

您可以使用 for..of loop 循环对象数组。

for (let item of items) {
    console.log(item); // Will display contents of the object inside the array
}

for..of 循环的优点之一是它们可以迭代的不仅仅是数组。您可以迭代任何类型的可迭代对象,包括地图和对象。如果您需要支持旧版浏览器,请确保使用转译器或 TypeScript 之类的东西。

如果你想遍历一个映射,语法与上面的基本相同,除了它同时处理键和值。

for (const [key, value] of items) {
  console.log(value);
}

对于我在 Javascript 中执行的几乎所有类型的迭代,我都使用 for..of 循环。此外,最酷的事情之一是它们也可以与 async/await 一起使用。


我更喜欢在 async 函数中使用它,而不是在 await Promise.all(array.map(async (element) => { 中使用单独的 try catch。更简洁的代码。
For..of 循环绝对是最好的。我相信它比 forEach 循环快 90% 左右。
T
Thierry
for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}

不过,这只是第二个问题的解决方案。
a
adiga

这是一个关于如何做到这一点的例子:)

var students = [{ name: "Mike", track: "track-a",成绩: 23, points: 400, }, { name: "james", track: "track-a",成绩: 2, points: 21, }, ] students.forEach(myFunction);功能 myFunction(item, index) { for (var key in item) { console.log(item[key]) } }


您将如何获取每个元素的 track 属性的值并将其分配给变量以在代码的另一部分中使用或插入?
a
adiga

循环遍历对象数组是一项非常基本的功能。这对我有用。

变种人 = []; person[0] = { firstName: "John", lastName: "Doe", age: 60 };变量 i,项目; for (i = 0; i < person.length; i++) { for (item in person[i]) { document.write(item + ": " + person[i][item] + "
"); } }


J
JDB

myArray[j.x] 在逻辑上不正确。

请改用 (myArray[j].x);

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}

@Cyborgx37 哦.. 我的意思是 jx 被视为不正确的变量名。
j
julien bouteloup

从 ES5+ 开始使用 forEach 方法非常简单。您可以直接更改数组中每个对象的每个属性。

myArray.forEach(function (arrayElem){ 
  arrayElem = newPropertyValue;
});

如果要访问每个对象的特定属性:

myArray.forEach(function (arrayElem){ 
      arrayElem.nameOfYourProperty = newPropertyValue;
    });

s
sangamkumar91

这会奏效。循环彻底 array(yourArray) 。然后循环遍历每个对象 (eachObj) 的直接属性。

yourArray.forEach( function (eachObj){
    for (var key in eachObj) {
        if (eachObj.hasOwnProperty(key)){
           console.log(key,eachObj[key]);
        }
    }
});

M
Matthew Morek

这是遍历对象数组的另一种方法(您需要在文档中为这些对象包含 jQuery 库)。

$.each(array, function(element) {
  // do some operations with each element... 
});

您的答案缺少有关需要加载 jQuery 库以使用 $.each 方法的关键信息。
H
Hemadri Dasari

接受的答案使用正常功能。因此,使用 forEach 上的箭头函数发布相同的代码并稍作修改

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

同样在 $.each 中,您可以使用如下箭头功能

 $.each(array, (item, index) => {
       console.log(index, item);
 });

a
adiga

const jobs = [ { name: "sipher", family: "sipherplus", job: "Devops" }, { name: "john", family: "Doe", job: "Devops" }, { name: "jim" ,家庭:“史密斯”,工作:“德沃普斯”}]; const txt = `

    ${jobs.map(job => `
  • ${job.name} ${job.family} -> ${job.job}
  • `).join(' ')}
` ; document.body.innerHTML = txt;

小心后面的蜱虫(`)


M
M S

数组对象迭代,使用 jQuery,(使用第二个参数打印字符串)。

$.each(array, function(index, item) {
       console.log(index, item);
});

a
adiga

var c = { myProperty: [ { name: 'this' }, { name: 'can' }, { name: 'get' }, { name: 'crazy' } ] }; c.myProperty.forEach(function(myProperty_element) { var x = myProperty_element.name; console.log('成员的名字是:' + x); })

这是我能够实现它的方法之一。


r
rajiv patel
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
    console.log(n.name)
}

P
PJ Brunet

这可能会帮助某人。也许这是 Node.js 中的一个错误。

var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;

这不起作用:

while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined

但这有效...

while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.

这也有效...

while ((arr[c]) && (arr[c].name)) { c++; }

但是简单地颠倒顺序是行不通的。我猜这里有某种内部优化会破坏 Node.js。

while ((arr[c].name) && (arr[c])) { c++; }

错误说数组未定义,但不是:-/ Node v11.15.0


J
Joseph Sang

我知道这已经很长时间了,但是对于遇到此问题的其他任何人,我的问题是我正在循环遍历仅包含一个数组的数组数组。像这样:

// array snippet (returned from here)
} else {
   callback([results])
}

我正在使用这样的数组

for(const result of results){
   console.log(result.x)
}

如您所见,我想要迭代的数组实际上在另一个数组中。删除方括号有帮助。节点 JS 和 MySQL。