javascript - 在数组中查找 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])
}
如何在数组中获取此类实例的索引?
解决方案
- 传递包含数组的引用。
- 要获取索引,请使用
Array.prototype.indexOf()
:
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}`));
推荐阅读
- c# - .Net Standard 2.0 库中的 Aspose.Cell 错误
- protractor - 在量角器中禁用浏览器启动以测试 REST 服务
- python-3.x - 命令在子进程或 os.popen 中不起作用,但在终端中起作用
- javascript - React 应用程序将在渲染上挂载 loadingbar.js,然后对象在 prop/state 更新时变为未定义
- magento - 由于 MIME 类型(“text/html”)不匹配(X-Content-Type-Options: nosniff),tyles.css 被阻止
- kubernetes - 在 Kubernetes AKS 中加密静态秘密数据?
- swift - 这是一个 Swift 编译器的错误,还是一个特性?.filter 似乎有问题
- sql-server - 在 VBA 中使用记录集时如何修复错误 7965?
- sql - 连接两个表并排除之前已经见过的行
- javascript - 使用js检查字母数字密码