JavaScript: Iterate through the array object to get the value


You can use the for loop or forEach method to traverse the array object, and obtain the corresponding value through the attribute name of the object.

1 Using a for loop

let arr = [
  {
    
     name: 'Alice', age: 18 },
  {
    
     name: 'Bob', age: 20 },
  {
    
     name: 'Charlie', age: 22 }
];

// 使用for循环
for (let i = 0; i < arr.length; i++) {
    
    
  let name = arr[i].name;
  let age = arr[i].age;
  console.log(name, age);
}

Output result:

Alice 18
Bob 20
Charlie 22

2 Using the forEach method

let arr = [
  {
    
     name: 'Alice', age: 18 },
  {
    
     name: 'Bob', age: 20 },
  {
    
     name: 'Charlie', age: 22 }
];

// 使用forEach方法
arr.forEach(item => {
    
    
  let name = item.name;
  let age = item.age;
  console.log(name, age);
});

Output result:

Alice 18
Bob 20
Charlie 22

3 The difference between the two methods

In JavaScript, there are many ways to traverse an array object, the most commonly used ones are for loop and forEach method. Their main differences are as follows:

  1. The for loop needs to manually specify the length and index of the array, but the forEach method does not.

  2. The for loop can use break and continue to control the flow of the loop, but the forEach method does not support it.

  3. The forEach method executes the callback function for each iteration, and the for loop can control the number of iterations or conditions as needed.

For example, suppose you have the following array objects:

const persons = [
  {
    
     name: 'Alice', age: 22 },
  {
    
     name: 'Bob', age: 30 },
  {
    
     name: 'Charlie', age: 25 }
];

Use a for loop to iterate over the array object:

for(let i = 0; i < persons.length; i++){
    
    
  console.log(persons[i].name);
}

Use the forEach method to iterate over the array object:

persons.forEach(person => console.log(person.name));

Both methods can output the name of each person in the array object, but the for loop can control the flow of the loop as needed, but the forEach method does not support it.

In short, both for loop and forEach methods have their advantages and limitations when traversing array objects, and developers should choose the appropriate method according to specific needs.

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/132067067