1、map()方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值;
注:map不会改变原数组,不会对空数组进行检测;
array.map(function(currentValue,index,arr), thisValue)
currentValue : 必须,当前元素的值;
index:可选,当前元素的索引值;
arr :可选 ,当前元素所属数组;
testMap () {
let arr = [1, 2, 3, 4]
let end = arr.map((item, index) => {
return item * 2
})
console.log(end) // [2, 4, 6, 8]
console.log(arr) // [1, 2, 3, 4]
},
testMap () {
let arr = [{name: 'a', age: 12}, {name: 'b', age: 13}]
arr.map((item, index) => {
item.b = index
})
console.log(arr) // [{name: "a", age: 12, b: 0},{name: "b", age: 13, b: 1}]
},
2、filter() 方法创建一个新的数组,数组中的元素是通过检查指定数组中符合条件的所有元素;
注:filter不会对空数组进行检测,不会改变原数组;
array.filter(function(currentValue,index,arr), thisValue)
testFilter () {
let arr = [{name: 'a', age: 12}, {name: 'b', age: 13}]
let end = arr.filter((item, index) => {
return item['age'] > 12
})
console.log(arr) // [{name: "a", age: 12},{name: "b", age: 13}]
console.log(end) // {name: "b", age: 13}
},
testFilter () {
let arr = [{name: 'a', age: 12}, {name: 'b', age: 13}]
arr.filter(item => item['age'] > 12).map(item => {
console.log(item) // {name: "b", age: 13
})
console.log(arr) // [{name: "a", age: 12},{name: "b", age: 13}]
},
3、some() 方法用于检测数组中的元素是否满足指定条件;此方法会依次执行数组的每个元素;
注:
- 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
- 如果没有满足条件的元素,则返回false。
array.some(function(currentValue,index,arr),thisValue)
返回值:布尔型,有满足条件的返回true,否则返回false。
testSome () {
let arr = [1, 2, 3, 4, 5, 6]
let end = arr.some(d => {
console.log(d) // 1 2 3 4
return d > 3
})
console.log(end) // true
},
testSome (val) {
let arr = [1, 2, 3]
if (arr.some(item => item === val)) {
return
}
arr.push(val)
console.log(arr) // [1, 2, 3, 4]
},
testSome(4)
4、every() 方法用于检测数组所有元素是否都符合指定条件,检测数组中的所有元素;
注:
- 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
- 如果所有元素都满足条件,则返回 true。
array.every(function(currentValue,index,arr), thisValue)
testEvery () {
let arr = ['a', 'b']
if (arr.every(d => isNaN(d))) {
console.log('成立')
}
},
testEvery () {
let list = [1, 2, 3, 4, 5]
let end = list.every((d, i) => {
console.log(d) // 1 2 3 4 5
return d > 0
})
console.log(end) // true
},
testEvery () {
let list = [1, 2, 3, 4, 5]
let end = list.every((d, i) => {
console.log(d) // 1
return d > 2
})
console.log(end) // false
},
5、forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注:没有返回值,只是针对每个元素调用func
array.forEach(function(currentValue, index, arr), thisValue)
testForeach () {
let list = [1, 2, 3, 4, 5]
let arr = []
list.forEach((d, i) => {
if (d > 3) {
arr.push(d)
}
})
console.log(arr) // [4, 5]
},