简体   繁体   中英

javascript indexOf class containing element

I have an array of elements of the same class, how can I search indexOf with only one element from the class

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

I need it to return 0 for this example as it matches listohashs[0].dlable that way i can get the corosponding tophash value

I have tried: console.log(listohashs.indexOf(0x001003)); and putting .dlable anywhere in there that I could think of.

can I search with a wild card in one of the element places? ie where * will match anything

searchohash = new Dhash(0x001003, *);
console.log(listohashs.indexOf(searchohash));

Is json what i should be using? im new to js and just started using json a few days ago

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. - MDN

You are looking for the element whose value if 0x001003 but listohashs is an array of objects. So you are comparing the object with 0x001003 which won't be equal so it will return -1 .

You can use findindex here, You have to find the index of the object whose Dlable property value is 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

indexOf only works if the argument is an actual element of the array, not just a property of it.

Use findIndex() to find an element using a function that will perform the appropriate comparison.

 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM