Js遍历数组
普通for:
let arr=[1,3,2,4,5]
for(let j = 0; j < arr.length; j++) {
…
}
foreach循环
// 没有返回值
// 遍历数组中的每一项,没有返回值,对原数组没有影响,不支持IE
//参数:item数组中的当前项, index当前项的索引, array原始数组;
arr.forEach((item,index,array)=>{
//执行代码
}
)
map循环
// 有返回值,可以return出来
// map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
let ary = [12,23,24,42,1];
let res = ary.map(function (item,index,ary ) {
return item*10;
})
console.log(res);//–>[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改
console.log(ary);//–>[12,23,24,42,1]; 原数组并未发生变化
For of 循环
// 可以正确响应break、continue和return语句
for (let value of myArray) {
console.log(value);
}
filter遍历
// 不会改变原始数组,返回新数组
var arr = [
{ id: 1, text: ‘aa’, done: true },
{ id: 2, text: ‘bb’, done: false }
]
console.log(arr.filter(item => item.done))//
Every循环
// every()是对数组中的每一项运行给定函数,如果该函数对每一项返回true,则返回true。
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.every( function( item, index, array ){
return item > 3;
}));
// 返回值:false
some遍历
// some()是对数组中每一项运行指定函数,如果该函数对任一项返回true,则返回true。
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.some( function( item, index, array ){
return item > 3;
}));
// 返回值:true
find遍历
// find()方法返回数组中符合测试函数条件的第一个元素,否则返回undefined。
var stu = [
{ name: ‘张三’, sex: ‘男’, age: 20 },
{ name: ‘王小毛’, sex: ‘男’, age: 20 },
{ name: ‘李四’, sex: ‘男’, age: 20 }
];
stu.find((element) => (element.name === ‘李四’));
// 返回值:{name: “李四”, sex: “男”, age: 20}
findIndex遍历
// 对于数组中的每个元素,findIndex 方法都会调用一次回调函数(采用升序索引顺序),直到有元素返回 true。
// 只要有一个元素返回 true,findIndex 立即返回该返回 true 的元素的索引值。如果数组中没有任何元素返回 true,则 findIndex 返回 -1。
// findIndex 不会改变数组对象。
[7,8,9].findIndex(x => x === 11);
// Returns an index value of -1.
ps:侵删