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