Javascript遍历数组的方法

Javascript遍历数组的方法

普通for循环:

const arr = [1, 2, 3, 4, 5, 6];
// for 循环
for (let i = 0; i < arr.length; i++) {
	console.log(arr[i]);
}

在ES5中新增了很多方便操作数组的方法,包括新5种数组的迭代方法:forEachmapfiltersomeevery
计算方法:reduce()
检测数组方法Array.isArray()
针对对象设计的:for..in
在ES6中又增加了for..of以及valuesentreskeysfind()findIndex()等 。
这些方法让操作数组更加优雅,趋近于函数式编程.。

1. ES5

ES5 Array5种迭代方法
ES5定义了5个迭代方法,IE9+支持。
  1. 检测数组里的元素是否满足条件;every()some() 返回Boolean值。
    不会对空数组进行检测;不会改变原始数组。
    every() 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测;如果所有元素都满足条件,则返回 true。
    some() 对数组的每一项运行给定函数, 如果函数对数组的任一项返回的true,return true

  2. 只做遍历,不返回任何值
    forEach():不可以用break、continue 对数组的每一项运行给定函数, 不返回任何值,只做函数操作 类似于 for () { do something }
    返回数组
    filter():对数组的每一项运行给定函数, 返回该函数会返回true的项组成的数组
    map():对数组的每一项运行给定函数, 返回每次函数调用结果组成的数组

    // every  一非则非
    arr.every(function(currentValue,index,arr) {
    //     // console.log(currentValue);  // 1  当前元素的值
    //     // console.log(index);  // 0  当前元素的索引值
    //     // console.log(arr); // [1, 2, 3, 4, 5, 6]  当前元素属于的数组对象
    
    //     console.log(currentValue < 0);   // false
    //     console.log(currentValue > 0);   // true
    })
    
     // some  一真则真
     // 1
     arr.some(function(currentValue,index,arr) {
     //     // console.log(currentValue);  // 1  当前元素的值
     //     // console.log(index);  // 0  当前元素的索引值
     //     // console.log(arr); // [1, 2, 3, 4, 5, 6]  当前元素属于的数组对象
     //
     //     // console.log(currentValue === 2);   // false true false false false false
     //     console.log(currentValue > 0);   // true true true true true true
     })
     // 2  阻止执行
     // console.log(arr.some(item =>  item === 2))  // true
     // let res = arr.some(function(currentValue,index,arr) {
     //     console.log(index);   // 0 1
     //     return currentValue === 2;  // 阻止执行
     // })
     // console.log(res);  // true
    
    // forEach
    // arr.forEach(function (item) {
    //     // console.log(item);
    //     // break;
    //     // continue
    // })
    
    // filter
    // console.log(arr.filter(item => item < 4));  // [1, 2, 3]
    
    // map
    // console.log(arr.map((item, index) => ({index: item + 9})))  // [{0: 10}, {1: 11}, {2: 12}, {3: 13}, {4: 14}, {5: 15}]
    
ES5中 for...in遍历以及 every()for...in对终止语句breakcontinue的处理

MDN提示: for...in不应该用于迭代一个 Array,其中索引顺序很重要
处理有key-value数据(比如属性用作“键”),需要检查其中的任何键是否为某值的情况时,推荐用for … in。

const arr = [1, 2, 3, 4, 5, 6];
// for
for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 2) {
        // break;
        // continue;
    }
    // console.log(arr[i]);  // 1  - break      1,3,4,5,6  - continue
}

// every  不可以用break、continue 但可以达到效果
arr.every(function (item) {
    // 1
    // console.log(item);   // 1  true,停止遍历


    // 2
    // if (item === 4) {
    //     // break;    //  无效
    //     // continue;  // 无效
    // }

    // 3
    // if (item === 4) {
    //     return true;
    // } else {
    //     console.log(item);
    //     return true;
    // }
    //
    // //   =>  简化
    // if (item === 4) {
    //
    // } else {
    //     console.log(item);
    // }
    // return true;   // 12356

    // 4
    // if (item === 4) {
    //     console.log(item)
    // }
    // return true;  // 4
})

// for...in
for (let index in arr) {
    // 1
    // console.log(index, arr[index]);   // 0 1, 1 2, 2 3, 3 4, 4 5, 5 6

    // 2  瑕疵: arr.a = 8;  for...in为对象设计的
    // arr.a = 8;
    // console.log(index, arr[index]);   // 0 1, 1 2, 2 3, 3 4, 4 5, 5 6, a 8

    // 3   break: 支持
    // if (index === 2) {
    //     break;
    // }
    // console.log(index, arr[index]);  // 0 1, 1 2, 2 3, 3 4, 4 5, 5 6
    //
    //
    // if (index === '2') {
    //     break;
    // }
    // console.log(index, arr[index]);  // 0 1, 1 2, 2 3

    // 4   continue: 支持
    // if (index === 2) {
    //     continue;
    // }
    // console.log(index, arr[index]);  // 0 1, 1 2, 2 3, 3 4, 4 5, 5 6
    //
    //
    // if (index === '2') {
    //     continue;
    // }
    // console.log(index, arr[index]);  // 0 1, 1 2, 3 4, 4 5, 5 6
}

2. ES6

for...of遍历
// for...of
// for (let item of arr) {
//     // 1
//     // console.log(item);  // 123456
// }
//
// // for...in和for...of差异:eg
// 1
// arr.push(7);
// for(let item of arr) {
//     // console.log(item); // 1 2 3 4 5 6
// }
// for(let key in arr) {
//     console.log(arr[key]); // 1 2 3 4 5 6 7
// }
const Price = {
    A: [1.5, 2.99 ,4.5],
    B: [99, 199 ,399],
    C: [10, 14 ,6]
}
// Object.prototype.D = '97';
for(let key in Price) {
    // console.log(key, Price[key]); // A: [1.5, 2.99 ,4.5], B: [99, 199 ,399], C: [10, 14 ,6]
}
// 若不想出现这种情况
for(let key in Price) {
    if(!Object.prototype.hasOwnProperty.call(Price, key)) continue;
    // console.log(Price[key]); //  [1.5, 2.99, 4.5]  [99, 199 ,399]  [10, 14 ,6]
}
keys():对键名(数组下标)的遍历
for (let i of arr.keys()) {
    // console.log(i);  // 0 1 2 3 4 5
}
values():对键值的遍历
for (let i of arr.values()) {
    // console.log(i);  // 1 2 3 4 5 6
}
entries():对键值对的遍历
for (let i of arr.keys()) {
// for (let i of arr.entries()) {
//     console.log(i);  // [0, 1] [1, 2] [2, 3] [3, 4] [4, 5] [5, 6]
// }
// for (let [index, elem] of arr.entries()) {
//     console.log(index, elem);  // 0 1 1 2 2 3 3 4 4 5 5 6
// }
find():返回数组中满足提供的测试函数的第一个元素的值
console.log(arr.find((value, index, arr) => value > 4));  // 5
findIndex():返回数组中满足提供的测试函数的第一个元素的索引 若没有找到对应元素则返回-1
console.log(arr.findIndex((value, index, arr) => value > 4));  // 4

3. 遍历数组时对空格的处理

ES5中:
forEach()filter()reduce()every()some()都会跳过空位。
map()会跳过空位,但会保留这个值
join()toString()会将空位视为undefined,而undefinednull会被处理成空字符串

// forEach方法
// [,'a'].forEach((x,i) => console.log(i)); // 1

// filter方法
// console.log(['a',,'b'].filter(x => true)); // ['a','b']

// every方法
// console.log([,'a'].every(x => x==='a')); // true

// reduce方法  求和,求乘积  计算数组中每个元素出现的次数  https://www.jianshu.com/p/e375ba1cfc47
// console.log([1,,2].reduce((x,y) => x+y)); // 3

// some方法
// console.log([,'a'].some(x => x !== 'a'));  // false

// map方法
// console.log([,'a'].map(x => 1)); // [empty, 1]

// join方法
// console.log([,'a',undefined,null].join('#')); // "#a##"

// toString方法
// console.log([,'a',undefined,null].toString()); // ",a,,"

ES6中:
明确将空位转为undefined

//entries()
// console.log([...[,'a'].entries()]); // [[0, undefined], [1, "a"]]
// const object1 = {
//     a: 'somestring',
//     b: 42
// };
// for (const [key, value] of Object.entries(object1)) {
//     console.log(`${key}: ${value}`);  // a: somestring  b: 42
// }

// keys()
// console.log([...[,'a'].keys()]); // [0,1]

// values()
// console.log([...[,'a'].values()]); // [undefined, "a"]

// find() 
// console.log([,'a'].find(x => true)); // undefined

// findIndex()  
// console.log([,'a'].findIndex(x => true)); // 0
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值