js判斷數據中是否存在某個值的方法


js判斷數據中是否存在某個值的方法:

  • indexOf(searchElement) :判斷數組中是否存在某個值,如果存在返回數組元素的索引,不存在則返回 -1。
  • includes(searchElement):判斷一個數組是否包含一個指定的值,如果存在返回 true,否則返回 false。
  • find(callback) :返回數組中滿足條件的第一個元素的值,如果沒有返回 undefined。
  • findIndex(callback): 返回數組中滿足條件的第一個元素的索引,如果沒有找到,返回 -1.

indexOf()

判斷數組中是否存在某個值,如果存在返回數組元素的索引,不存在則返回 -1

let arr = ["a", "b", "c"]
let index = arr.indexOf('c')
console.log(index) // c存在,返回c的索引:2
let i = arr.indexOf('d')
console.log(i) // d不存在,返回:-1

includes(searchElement[,fromIndex])

判斷一個數組是否包含一個指定的值,如果存在返回 true,否則返回 false。

參數:

  • searchElement --- 需要查找的值
  • fromIndex --- 索引,可選。從該索引處開始查找 searchElement。如果為負值,則按升序從 array.length + fromIndex 的索引開始搜索,默認為 0。
let arr = ["a", "b", "c"]
let res = arr.includes('a')
console.log(res) // true
let res1 = arr.includes('d')
console.log(res1) // false
// 從 -2 + arr.length = 1 開始查找
let res2 = arr.includes('c', -2) 
console.log(res2) // true

find(callback[, thisArg])

返回數組中滿足條件的第一個元素的值,如果沒有返回 undefined。

參數:callback

  • element 當前遍歷到的元素。
  • index 當前遍歷到的索引。
  • array 數組本身。

參數:thisArg(可選)---指定 callback 的 this 參數

// ---------- 元素是普通字面值 ----------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => {
    return item > 8;
});
console.log(result) // 結果: 12
// ---------- 元素是對象 ----------
let items = [
    {id: 1, name: 'something'},
    {id: 2, name: 'anything'},
    {id: 3, name: 'nothing'},
    {id: 4, name: 'anything'}
];
let item = items.find(item => {
    return item.id == 3;
});
console.log(item) // 結果: Object { id: 3, name: "nothing" }

findIndex(callback[, thisArg])

返回數組中滿足條件的第一個元素的索引,如果沒有找到,返回 -1.

參數:callback

  • element 當前遍歷到的元素。
  • index 當前遍歷到的索引。
  • array 數組本身。

參數:thisArg(可選)---指定 callback 的 this 參數

// ---------- 元素是普通字面值 ----------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.findIndex(item => {
    return item > 8;
});
console.log(result) // 返回第一個大於8的值得索引:0

// ---------- 元素是對象 ----------
let items = [
    {id: 1, name: 'something'},
    {id: 2, name: 'anything'},
    {id: 3, name: 'nothing'},
    {id: 4, name: 'anything'}
];
let item = items.findIndex(item => {
    return item.id == 3;
});
console.log(item) // 返回索引為 2

本文轉自:https://segmentfault.com/a/1190000014202195


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM