【问题标题】:Getting an array element index in JavaScript在 JavaScript 中获取数组元素索引
【发布时间】:2014-06-23 12:17:56
【问题描述】:

是否可以让数组的元素告诉它在 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"

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

【问题讨论】:

    标签: javascript arrays object methods indexing


    【解决方案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
    

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

    【讨论】:

      【解决方案2】:

      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 就足够了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 1970-01-01
        相关资源
        最近更新 更多