首页 > 解决方案 > 在数组中查找 JS 类本身

问题描述

const Myclass = function(n) {
   this.name = n;
   this.getIndex= function(array) {
      //how to return array index
   }
   this.getName= function() {
      return this.name;
   }
}

var array = [];

array[1] = new Myclass('Eminem');
array[2] = new Myclass('ugly boy');
array[10] = new Myclass('Slim Shady');

/// will shuffle this array (randomly change indexes)

for(let i in array) {
  (function(_i){    
       console.log('My name is '+_i.getName()+ ' I\'am sitting at index '._i.getIndex(array))
  })(array[i])
}

如何在数组中获取此类实例的索引?

标签: javascript

解决方案


class Person {
  
  constructor (name, arr) {
    this.name = name;
    this.array = arr;
    this.array.push(this);
  }
  
  get index() {               
    return this.array.indexOf(this);
  }
}

const persons = [];
// Populate persons with Person classes
['Eminem', 'Ugly Boy', 'Slim Shady'].forEach(name => new Person(name, persons));

// Let's say the persons Array is shuffled...
persons.forEach(P => console.log(`My name is ${P.name} I'm at index ${P.index}`));


推荐阅读