淘先锋技术网

首页 1 2 3 4 5 6 7
在JavaScript开发中,循环对象数组是经常用到的操作。对象数组指的是包含多个对象的数组,每一个对象都有一个或多个属性。那么如何遍历其中的每一个对象呢?下面我们来谈一下一些常用的方法。 1. for循环 for循环是最常用的遍历方式,代码可以如下: ```javascript const arr = [ { name: 'John', age: 25 }, { name: 'Mary', age: 31 }, { name: 'Tom', age: 24 }, ]; for (let i = 0; i< arr.length; i++) { console.log(`${arr[i].name} is ${arr[i].age} years old.`); } ``` 以上代码输出的内容为: ``` John is 25 years old. Mary is 31 years old. Tom is 24 years old. ``` 可以看到,我们通过for循环遍历了obj数组中的每一个元素,并将其属性name和age输出了出来。 2. forEach方法 ES5中引入了forEach方法,它能够让我们更加简便地遍历数组。代码如下: ```javascript arr.forEach((obj) =>{ console.log(`${obj.name} is ${obj.age} years old.`); }); ``` 以上代码输出内容与上例类似。 需要注意的是,forEach方法不支持break或return语句来中途跳出循环。 3. for...in循环 我们也可以使用for...in循环来遍历数组,不过此时我们需要将数组转换为对象。代码如下: ```javascript const arr = [ { name: 'John', age: 25, sex: 'male' }, { name: 'Mary', age: 31, sex: 'female' }, { name: 'Tom', age: 24, sex: 'male' }, ]; for (let i in arr) { console.log(`${arr[i].name} is ${arr[i].age} years old and he/she is ${arr[i].sex}.`); } ``` 以上代码输出内容为: ``` John is 25 years old and he/she is male. Mary is 31 years old and he/she is female. Tom is 24 years old and he/she is male. ``` 可以看到,for...in循环可以遍历数组中的每一个元素,输出其属性值。但是需要注意的是,当我们使用for...in循环遍历对象数组时,顺序是不可控的。 4. for...of循环 ES6中新增了for...of循环,可以用来遍历可遍历对象(包括数组、字符串、Map、Set等)。代码如下: ```javascript for (let obj of arr) { console.log(`${obj.name} is ${obj.age} years old and he/she is ${obj.sex}.`); } ``` 以上代码输出内容与上例类似。 需要注意的是,for...of循环只能遍历可遍历对象,而不能遍历普通对象。 总结 本文介绍了JavaScript中常用的几种循环对象数组的方式,分别是for循环、forEach方法、for...in循环和for...of循环。需要注意的是,不同的方式适用于不同的场景,我们需要根据具体情况来选择最合适的方式。