語法節
arr.some(callback(element[, index[, array]])[, thisArg])
參數節
-
callback
-
用來測試每個元素的函數,接受三個參數:
-
element
- 數組中正在處理的元素。
-
index
可選 - 數組中正在處理的元素的索引值。
-
array
可選 -
some()
被調用的數組。
-
-
thisArg
可選 -
執行
callback
時使用的this
值。
返回值節
如果回調函數返回任何數組元素的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