我有一組相同類的元素,如何只使用類中的一個元素搜索 indexOf
class Dhash {
constructor(Dlable, tophash) {
this.Dlable = Dlable;
this.tophash = tophash;
}
}
let listohashs = [];
listohashs[0] = new Dhash(0x001003, 0xfffffffffffffffffffffffffffffffffa);
listohashs[1] = new Dhash(0x011003, 0xfffffffffffffffffffffffffffffffffb);
listohashs[2] = new Dhash(0x021003, 0xfffffffffffffffffffffffffffffffffc);
console.log(listohashs.indexOf(0x001003)); // <-- here be the problem
我需要它為這個例子回傳 0 因為它匹配listohashs[0].dlable這樣我可以獲得 corospondingtophash值
我試過:
console.log(listohashs.indexOf(0x001003));并把.dlable我能想到的任何地方放在那里。
我可以在元素位置之一使用通配符進行搜索嗎?即 * 將匹配任何內容
searchohash = new Dhash(0x001003, *);
console.log(listohashs.indexOf(searchohash));
我應該使用 json 嗎?我是 js 新手,幾天前才開始使用 json
uj5u.com熱心網友回復:
indexOf() 方法回傳可以在陣列中找到給定元素的第一個索引,如果不存在,則回傳 -1。- MDN
您正在尋找其值 if 0x001003butlistohashs是物件陣列的元素。因此,您正在比較0x001003不相等的物件,因此它將回傳-1.
您可以findindex在這里使用,您必須找到index其Dlable屬性值為0x001003
class Dhash {
constructor(Dlable, tophash) {
this.Dlable = Dlable;
this.tophash = tophash;
}
}
let listohashs = [];
listohashs[0] = new Dhash(0x001003, 0xfffffffffffffffffffffffffffffffffa);
listohashs[1] = new Dhash(0x011003, 0xfffffffffffffffffffffffffffffffffb);
listohashs[2] = new Dhash(0x021003, 0xfffffffffffffffffffffffffffffffffc);
console.log(listohashs.findIndex((o) => o.Dlable === 0x001003)); // <-- here be the problem
uj5u.com熱心網友回復:
indexOf 僅當引數是陣列的實際元素時才有效,而不僅僅是陣列的屬性。
用于findIndex()使用將執行適當比較的函式查找元素。
class Dhash {
constructor(Dlable, tophash) {
this.Dlable = Dlable;
this.tophash = tophash;
}
}
let listohashs = [];
listohashs[0] = new Dhash(0x001003, 0xfffffffffffffffffffffffffffffffffa);
listohashs[1] = new Dhash(0x011003, 0xfffffffffffffffffffffffffffffffffb);
listohashs[2] = new Dhash(0x021003, 0xfffffffffffffffffffffffffffffffffc);
console.log(listohashs.findIndex(h => h.Dlable == 0x001003));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350985.html
標籤:javascript 节点.js 数组 班级 指数
