let obj = arr.find(item => item.id == 1) console.log(obj); // 结果:{id: 1, name: '张一', age: 25, class: '一班'} 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 方法6、filter() 我们可以使用 Array.filter(
var newArr = arr.filter(item => item > 5); console.log(newArr); //[6, 7] 1. 2. 3. array.filter(function(currentValue, index, arr),thisValue) currentValue : 必需。当前元素 index:可选。当前元素的索引值 arr: 可选。当前元素所属的数组对象 thisValue: 可选。 传递给函数的值一般用 ...
这意味着 indexOf 只会在数组中查找值,而 findIndex 将让你决定如何查找索引。 下面是Array.prototype.findIndex方法与Array.prototype.indexOf方法之间差异的直观示例: const exampleArray = ["a", "b", "c"] exampleArray.indexOf("b") // 1 exampleArray.findIndex(arrayItem => arrayItem === "b")...
log(arr.indexOf(findVal)) // -1 console.log(arr.findIndex(val => compare(val, findVal))) // 3 /** * @name 两值比较 * @param {*} obj1 值1 * @param {*} obj2 值2 * @returns {Boolean} true 相等 false 不等 */ export function compare (obj1, obj2) { const type = get...
if (item === 4) return console.log(item) // 1, 2, 3, 5 }) forEach可以采用抛出异常(try catch)来终止循环 const arr = [1,2,3,4,5] try{ arr.forEach((item) => { if (item === 3) { throw new Error('end') } console.log(item) // 1, 2 ...
list=this.array1.filter(item=>{returnarray2.indexOf(item) !== -1}) indexOf(); indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。 注释:indexOf() 方法对大小写敏感! 注释:如果要检索的字符串值没有出现,则该方法返回 -1。
The findIndex() method returns the index of the first element in an array that pass a test (provided as a function).The findIndex() method executes the function once for each element present in the array:If it finds an array element where the function returns a true value, findIndex()...
We can loop through each array element and find any element or its position based on any condition. Using for loop constarr=['Gold','Silver','Platinum','Iron']; letisPresent=false; for(letitemofarr) { if(item==='Silver')isPresent=true; ...
JS find 和 findIndex 方法 find 返回符合条件的第一个元素 如果没有符合条件的元素则返回 undefined 注意: find 对空数组不执行 find 不改变原数组 代码语言:javascript let[1,2,3letfind=arrfinditem)=>{returnitem%2===find// 2 findIndex 返回符合条件的第一个元素位置 如果没有符合条件的元素则返回 -...
findIndex() 方法返回数组中通过测试的第一个元素的索引(作为函数提供)。 findIndex() 方法对数组中存在的每个元素执行一次函数: 如果找到函数返回 true 值的数组元素,则 findIndex() 返回该数组元素的索引(并且不检查剩余值) 否则返回 -1 注释:findIndex() 不会为没有值的数组元素执行函数。