繁体   English   中英

在JavaScript中获取数组元素索引

[英]Getting an array element index in JavaScript

是否可以让数组的元素告诉其在JavaScript中的位置? 如果可能的话,当您有一个对象数组并且需要调用对象字符串中一个方法之一时,它可能会派上用场。 您可以将其索引作为方法参数传递,但这似乎很杂乱,可能不必要。

理想情况下,应该是这样的:

function ArrayType(){

    this.showIdentity = function(){ 
        alert(this.indexOf()); // This obviously doesn't work, but I'm looking for
                                // a method that will return the index of "this" 
                                // in its parent array.
    }
}

var myArray = new Array();

myArray[0] = new ArrayType;
myArray[1] = new ArrayType;
myArray[1].showIdentity(); // Should alert "1"

有谁知道解决这个问题的方法(除了将索引与方法一起传递之外)?

您可以这样做:

function ArrayType(parent){
    var p = parent;
    this.showIdentity = function(){ 
        alert(p.indexOf(this));
    }
}

var myArray = new Array();

myArray[0] = new ArrayType(myArray);
myArray[1] = new ArrayType(myArray);
myArray[1].showIdentity(); // 1

这为元素提供了对父级的引用,使它们可以在父级中找到自己。

indexOf方法实际上是Array.prototype一部分,因此您应该从数组对象而不是实际对象中调用它:

function ArrayType(){

    this.showIdentity = function(){ 
       console.log( myArray.indexOf(this) );
    };

};

var myArray = new Array();

myArray[0] = new ArrayType();
myArray[1] = new ArrayType();

myArray[0].showIdentity();

这应该工作。

如果您想使用不同的数组,我可以考虑两种解决方案。 首先是简单地传递想要的数组作为引用,然后让对象询问该数组内的索引:

function ArrayType(){

    this.showIdentity = function(array){ 

       console.log( array.indexOf(this) );

    };
};

var myArray       = new Array();
var mySecondArray = new Array();

var a  = new ArrayType();
var a2 = new ArrayType();

myArray.push(a, a2);
mySecondArray.push(a2, a);

a.showIdentity(myArray);  // 0
a.showIdentity(mySecondArray); // 1

第二个方法是向Array原型添加一个方法,而不是让它成为其中对象的方法:

Array.prototype.findIndex = function(object) {
  console.log( this.indexOf(object) );
};

function ArrayType(){};

var myArray       = new Array();
var mySecondArray = new Array();

var a  = new ArrayType();
var a2 = new ArrayType();

myArray.push(a, a2);
mySecondArray.push(a2, a);

myArray.findIndex(a); // 0
myArray.findIndex(a2); // 1

当然,原型路线仅在您想要除获取索引以外要做更多工作的情况下才有效。 如果只需要索引, indexOf就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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