js如何獲取對象在數(shù)組中的index
更新時間:2022年09月01日 14:34:11 作者:邱六崇
這篇文章主要介紹了js如何獲取對象在數(shù)組中的index,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
獲取對象在數(shù)組中的index
需求:數(shù)組中的元素是對象,需要獲取對象在數(shù)組中的index
方法:使用findIndex方法
原數(shù)據(jù):
const ?array = [
?? ?{
?? ??? ?id:1,
?? ??? ?name:'張xx'
?? ?},
?? ?{
?? ??? ?id:2,
?? ??? ?name:'王xx'
?? ?}
]方法:
const index = array.findIndex(function(val){
?? ?return val.id === 1?
})
// 如果有多個滿足,返回第一個的index
console.log(index) // 0數(shù)組的indexOf()方法
var arr = [10, 20, 30, 40, 50, 20, 56, 34, 20];
// var ret = arr.reverse(); // 數(shù)組的倒置, 數(shù)組名.reverse()
// console.log(ret);
//查找某個元素是不是在數(shù)組中
// 數(shù)組名.includes(元素) 。這個方法的返回值是 布爾值 false 或者 true
/* var ret = arr.includes(40); // 數(shù)組名.includes(元素)
console.log(ret); */
// 獲取某個元素第一次出現(xiàn)在數(shù)組中時的 下標即索引
// 數(shù)組名.indexOf(); 返回值是數(shù)組的下標;如果不在 就返回 -1
var ret = arr.indexOf(20);
console.log(ret);
var ret1 = arr.indexOf(20, 5); // 第二個參數(shù)表示從哪個下標 開始,查找,包含此下標元素
console.log(ret1);以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

