ES5中的常用的数组方法

  1. isArray方法
    检验变量是否包含数组数据
    var months = ['January', 'Febraury', 'March', 'April', 'May'];
    alert(Array.isArray(months)); //true
  2. forEach方法
    var months = ['January', 'Febraury', 'March', 'April', 'May'];
    months.forEach(function(value, index, fullArray){
    alert(value + ' is month number ' + (index+1) + ' of ' + fullArray.length);
    }); //循环遍历数组 第一个参数是数组值,第二个是索引,第三个是当前数组。(下面的参数同样如此)
  3. every和some方法
    //every方法遍历数组每一个元素,将每一个元素和一个条件比较,都满足返回true,否则为false.
    var months = ['January', 'Febraury', 'March', 'April', 'May'];
    var every = months.every(function(value, index, fullArray){
    return value.indexOf('r') >= 0;
    });
    alert(every); //false
    //some也是遍历数组,但只要任意一个满足条件就返回true,否则为false
    var months = ['January', 'Febraury', 'March', 'April', 'May'];
    var some = months.some(function(value, index, fullArray){
    return value.indexOf('r') >= 0;
    });
    alert(some); //true
  4. map方法
    //返回一个处理后的数组,原数组保持不变
    var months = ['January', 'Febraury', 'March', 'April', 'May'];
    months.map(function(value, index, fullArray){
    return value + ' is month number ' + (index+1) + ' of ' + fullArray.length;
    }); // ["January is month number 1 of 5", "Febraury is month number 2 of 5", "March is month number 3 of 5", "April is month number 4 of 5", "May is month number 5 of 5"]
  5. filter方法
    var months = ['January', 'Febraury', 'March', 'April', 'May'];
    var filterMonths = months.filter(function(value, index, fullArray){
    return value.indexOf('r') >= 0;
    });
    console.log(filterMonths); // ["January", "Febraury", "March", "April"]

你可能感兴趣的:(ES5中的常用的数组方法)