es5-Array

es5_Array

迭代方法:

  • forEach:

let arr = [1,4,2,3,4,5];
    arr.forEach(function(value,index){
        console.log(index);
        console.log(value);
    })
    //显示0 1 1 4 2 2 3 3 4 4 5 5 
  • map:

let arr1 = arr.map(function(value){
        return value*2+1;
    })
    console.log(arr1);//显示[3, 9, 5, 7, 9, 11];
  • filter:

let arr2 = arr.filter(function(value){
        return value>2;
    })
    console.log(arr2);//显示: [4, 3, 4, 5];
  • some:

let arr3 = arr.some(function(value){
        return value>5;
    })
    console.log(arr3);//显示false
    //只要有一个条件满足就返回true;
  • every:

let arr4 = arr.every(function(value){
        return value>0;
    })
    console.log(arr4);//显示true;
    //必须所有条件都满足才返回true,其它情况都返回false;
  • 方法:

console.log(arr.indexOf(4));//显示:1;
    console.log(arr.indexOf(5)>-1);//打印true;
    //indexOf:从前往后找,找第一个;
            
    console.log(arr.lastIndexOf(4));//打印4;
            
    //lastindexOf:从后边往前找,找最后一个;

缩小方法:

  • reduce,reduceRight:

let arr5 = arr.reduce(function(last,now){
        return last+now;
    },0);
    console.log(arr5);//显示19;
    let arr6 = arr.reduceRight(function(last,now){
        return last+now;
    },0);
    console.log(arr6);//打印19;
    //reduce:从左往右算,reduceRight:从右往左算,它俩结果是一样的;

判断方法:

let x = 2;
    console.log(Array.isArray());//打印false;
    //Array.isArray:判断一个变量是否是数组;

注释:这些方法不兼容ie8;

    原文作者:骚胖
    原文地址: https://segmentfault.com/a/1190000010312859
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞