let arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) {
console.log(arr[i])
}
// 1
// 2
// 3
let arr = [1, 2, 3]
arr.forEach(function (item, index, arr) {
console.log(item, index)
})
// 1 0
// 2 1
// 3 2
for 循环可以在循环体中终止或跳过该循环,forEach不可以
let arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
continue // 跳过
}
if (arr[i] === 3) {
break
}
console.log(arr[i])
}
// 2
let arr = [1, 2, 3]
let result = arr.map(function (value) {
value += 1
return value
})
console.log(arr, result)
//(3) [1, 2, 3] (3) [2, 3, 4]
let arr = [1,2,3]
let result = arr.filter(function (value) {
return value === 2
})
console.log(arr, result)
// (3) [1, 2, 3] [2]
let arr = [1,2,3]
let result = arr.some(function (value) {
return value === 2
})
console.log(arr, result )
// (3) [1, 2, 3] true
let arr = [1,2,3]
let result = arr.every(function (value) {
return typeof value === 'number'
})
console.log(arr, result)
// (3) [1, 2, 3] true
prev 表示上一次调用函数的返回值
cur 表示当前正在处理的元素
index 当前元素的索引
arr 原数组
initValue 传递给函数的初始值
let arr = [1, 2, 3]
let sum = arr.reduce(function(prev, cur, index, arr){
return prev + cur
}, 0)
console.log(sum)
// 6
let arr = [1, 2, 3]
let max = arr.reduce(function (prev, cur) {
return Math.max(prev, cur)
})
console.log(arr, max)
// (3) [1, 2, 3] 3
let arr = [1, 2, 3, 2, 4]
let res = arr.reduce(function (prev, cur) {
prev.indexOf(cur) == -1 && prev.push(cur)
return prev
}, [])
console.log(res)
// (4) [1, 2, 3, 4]
1.特点:不仅循环遍历了数组本身,同时循环遍历了数组原型链上的属性和方法
let arr = [1, 2, 3]
Array.prototype.name ='xiaoxiao'
Array.prototype.foo = function () {
console.log('foo')
}
for (let index in arr) {
console.log(index, arr[index])
}
//0 1
// 1 2
// 2 3
// name xiaoxiao
// foo ƒ () {
// console.log('foo')
// }
返回第一个符合条件的元素
let arr = [1,2,3,4, 2]
let res = arr.find(function (value) {
return value === 2
})
console.log(res, arr)
// 2 (5) [1, 2, 3, 4, 2]
// 返回第一个数字2
返回第一个符合条件的元素的索引
let arr = [1,2,3,4, 2]
let res = arr.findIndex(function(value) {
return value === 2
})
console.log(arr, res)
// (5) [1, 2, 3, 4, 2] 1
let arr = [
{
name: '张三',
age: 18
},
{
name: '赵四',
age:20
}
]
for( let item of arr) {
console.log(item, arr)
}
// {name: '张三', age: 18}, Object (2) [{…}, {…}]
// {name: '赵四', age: 20}, Object (2) [{…}, {…}]
let arr = [
{
name: '张三',
age: 18
},
{
name: '赵四',
age:20
}
]
for( let item of arr.values()) {
console.log(item, arr)
}
// {name: '张三', age: 18}, Object (2) [{…}, {…}]
// {name: '赵四', age: 20}, Object (2) [{…}, {…}]
let arr = [
{
name: '张三',
age: 18
},
{
name: '赵四',
age:20
}
]
for( let item of arr.keys()) {
console.log(item, arr)
}
// 0 (2) [{…}, {…}]
// 1 (2) [{…}, {…}]
let arr = [
{
name: '张三',
age: 18
},
{
name: '赵四',
age:20
}
]
for( let [index, item] of arr.entries()) {
console.log(index, item)
}
// 0 {name: '张三', age: 18}
// 1 {name: '赵四', age: 20}