美文网首页
map 与 for 循环的区别

map 与 for 循环的区别

作者: 安北分享 | 来源:发表于2021-09-16 10:33 被阅读0次

    map 与 for 循环的区别:

    Talk is cheap. Show me the code.

    第 1 组:
    1️⃣

    const arr1 = [1, 2, 3];
    const arr2 = [];
    for(let i = 0; i < arr1.length; i++) {
      arr2.push(arr1[i] * 2);
    }
    console.log(arr2); // [ 2, 4, 6 ]
    

    2️⃣

    const arr1 = [1, 2, 3];
    const arr2 = arr1.map(item => item * 2);
    console.log(arr2);  // [ 2, 4, 6 ]
    

    第 2 组:
    1️⃣

    const birthYear = [1975, 1997, 2002, 1995, 1985];
    const ages = [];
    for(let i = 0; i < birthYear.length; i++) {
      let age = 2018 - birthYear[i];
      ages.push(age);
    }
    console.log(ages); // [ 43, 21, 16, 23, 33 ]
    

    2️⃣

    const birthYear = [1975, 1997, 2002, 1995, 1985];
    const ages = birthYear.map(year => 2018 - year);
    console.log(ages); // [ 43, 21, 16, 23, 33 ]
    

    第 3 组:
    1️⃣

    const persons = [
      { name: 'Peter', age: 16 },
      { name: 'Mark', age: 18 },
      { name: 'John', age: 27 },
      { name: 'Jane', age: 14 },
      { name: 'Tony', age: 24},
    ];
    const fullAge = [];
    for(let i = 0; i < persons.length; i++) {
      if(persons[i].age >= 18) {
        fullAge.push(persons[i]);
      }
    }
    console.log(fullAge);
    

    2️⃣

    const persons = [
      { name: 'Peter', age: 16 },
      { name: 'Mark', age: 18 },
      { name: 'John', age: 27 },
      { name: 'Jane', age: 14 },
      { name: 'Tony', age: 24},
    ];
    const fullAge = persons.filter(person => person.age >= 18);
    console.log(fullAge);
    

    第 4 组:
    1️⃣

    const arr = [5, 7, 1, 8, 4];
    let sum = 0;
    for(let i = 0; i < arr.length; i++) {
      sum = sum + arr[i];
    }
    console.log(sum); // 25
    

    2️⃣

    const arr = [5, 7, 1, 8, 4];
    const sum = arr.reduce(function(accumulator, currentValue) {
      return accumulator + currentValue;
    });
    console.log(sum); // 25
    

    参考原文

    相关文章

      网友评论

          本文标题:map 与 for 循环的区别

          本文链接:https://www.haomeiwen.com/subject/sxkrgltx.html