2

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;


songze
211 声望13 粉丝

该来的总会来,该走的不挽留!


« 上一篇
es5_Object
下一篇 »
React表单