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种数组的迭代方法:forEach
、map
、filter
、some
、every
;
计算方法:reduce()
;
检测数组方法Array.isArray()
;
针对对象设计的:for..in
;
在ES6中又增加了for..of
以及values
、entres
、keys
、find()
、findIndex()
等 。
这些方法让操作数组更加优雅,趋近于函数式编程.。
1. ES5
ES5 Array5种迭代方法
ES5定义了5个迭代方法,IE9+支持。
-
检测数组里的元素是否满足条件;
every()
、some()
返回Boolean
值。
不会对空数组进行检测;不会改变原始数组。
every()
如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测;如果所有元素都满足条件,则返回 true。
some()
对数组的每一项运行给定函数, 如果函数对数组的任一项返回的true,return true -
只做遍历,不返回任何值
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
对终止语句break
、continue
的处理
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
,而undefined
和null
会被处理成空字符串
// 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