Array循环

  大家平常经常会遇到数组的循环,最常用的可能是for循环以及forEach,但是自从ES6之后有了map、set等属性 ,这对我们精简代码起到了很大的作用,今天我就罗列下几种常用的数组循环方式,以及它们的区别。

  let arr = ['name', 'age', 'sex'];
  1. // forEach
  let arrforeach = [];
  arr.forEach(function(item, index){
    arrforeach.push(index+'-'+item);
  });
  console.log(arrforeach); //["0-name", "1-age", "2-sex"]

  2. // map 将arr.map()赋值给新值arrmap,会发现新值arrmap是经过arr改造的另一个数组
  let arrmap = arr.map(function (item, index) {
    return index+'-'+item
  });
  console.log(arrmap); //["0-name", "1-age", "2-sex"]

  3. // filter 筛选符合条件的所有元素
  let arrfilter = arr.filter(function (item, index) {
    return index > 0;
  });
  console.log(arrfilter); //["age", "sex"]

  4. // find 返回符合条件的第一个元素,也就是找到为止,找不到返回undefined
  let onlyitem = arr.find(function(item, index){
    return item.length === 3;
  });
  console.log(onlyitem); //age

  5. // some 测试数组中是否至少有一个元素满足条件,有则返回true 无则返回false
  let booltrue = arr.some(function(item, index){
    return index > 1;
  });
  console.log(booltrue); //true
  let boolfalse = arr.some(function(item, index){
    return index > 2;
  });
  console.log(boolfalse); //false

  本文参考Array.prototype, 链接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  

    

原文地址:https://www.cnblogs.com/fewhj/p/7843370.html