find()
- 返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
-
find
方法对数组中的每一项元素执行一次callback
函数,直至有一个 callback 返回true
。当找到了这样一个元素后,该方法会立即返回这个元素的值,否则返回 undefined。 - 注意
callback
函数会为数组中的每个索引调用即从0
到length - 1
,而不仅仅是那些被赋值的索引,这意味着对于稀疏数组来说,该方法的效率要低于那些只遍历有值的索引的方法。 -
callback
函数带有3个参数:当前元素的值、当前元素的索引,以及数组本身。 - 如果提供了
thisArg
参数,那么它将作为每次callback
函数执行时的this
,如果未提供,则使用 undefined。 -
find
方法不会改变数组。
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
var arr = [
{name: 'fx', age: 18},
{name: 'wfd', age: 19},
]
var arrTest = arr.find((item, index, array) => {
console.log('当前值:' + JSON.stringify(item), '当前值的索引' + index, '当前数组' + array)
return item.age >= 18
})
console.log(arrTest)
var arr = [
{name: 'fx', age: 18},
{name: 'wfd', age: 19},
]
var arrTest = arr.find((item, index, array) => {
console.log('当前值:' + JSON.stringify(item), '当前值的索引' + index, '当前数组' + array)
return item.name === 'wfd'
})
console.log(arrTest)
下面的例子展示了如何从一个数组中寻找质数(如果找不到质数则返回 undefined)
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
当在回调中删除数组中的一个值时,当访问到这个位置时,其传入的值是 undefined:
findIndex()
- 返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
-
findIndex
方法对数组中的每个数组索引0..length-1
(包括)执行一次callback
函数,直到找到一个callback
函数返回真实值(强制为true
)的值。 - 如果找到这样的元素,
findIndex
会立即返回该元素的索引。 - 如果回调从不返回真值,或者数组的
length
为0,则findIndex
返回-1。 - 与某些其他数组方法(如Array#some)不同,在稀疏数组中,即使对于数组中不存在的条目的索引也会调用回调函数。
- 回调函数调用时有三个参数:元素的值,元素的索引,以及被遍历的数组。
- 如果一个
thisArg
参数被提供给findIndex
, 它将会被当作this
使用在每次回调函数被调用的时候。如果没有被提供,将会使用 undefined。findIndex
不会修改所调用的数组。
以下示例查找数组中素数的元素的索引(如果不存在素数,则返回-1)。
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
var arr = [
{name: 'fx', age: 18},
{name: 'wfd', age: 19},
]
var arrTest = arr.findIndex((item, index, array) => {
console.log('当前值:' + JSON.stringify(item), '当前值的索引' + index, '当前数组' + array)
return item.name === 'wfd'
})
console.log(arrTest)
标签:findIndex,log,索引,详解,数组,find,name From: https://blog.51cto.com/u_13028258/5754003