语法节
arr.some(callback(element[, index[, array]])[, thisArg])
参数节
-
用来测试每个元素的函数,接受三个参数:
- 数组中正在处理的元素。
- 数组中正在处理的元素的索引值。
-
some()
被调用的数组。
element
index
可选array
可选 -
执行
callback
时使用的this
值。
callback
thisArg
可选
返回值节
如果回调函数返回任何数组元素的truthy值,则返回true
;否则为false
。
// 一、测试数组元素的值
const a = [11, 50, 40, 3, 5, 80, 90, 4];
const arr = [];
a.some((item, index, array) => {
console.log(item);
// test.html:26 11
// test.html:26 50
// test.html:26 40
// test.html:26 3
// test.html:26 5
// test.html:26 80
// test.html:26 90
if (item > 80) {
return arr.push(item);
}
})
console.log(arr);
// [90]
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
//二、 判断数组元素中是否存在某个值
// 模仿 includes()方法, 若元素在数组中存在, 则回调函数返回值为 true :
var fruits = ['apple', 'banana', 'mango', 'guava'];
var fruitsNew = [];
function checkAvailability1(arr, val) {
return arr.some(arrVal => {
val == arrVal
})
}
checkAvailability1(fruits, 'kela'); // false
checkAvailability1(fruits, 'banana'); // true
// 三、根据条件截取更新数据
function checkAvailability2(val) {
fruits.some((item, i) => {
if (item == val) {
fruits.splice(i, 1)
}
})
}
checkAvailability2('banana');
console.log(fruits);
// ["apple", "mango", "guava"]
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/some