在原型 Javascript 数组中查找对象的索引



我正在使用jQuery移动版创建一个应用程序,需要在原型数组中获取对象的索引。

对象,调用团队,如下所示:

var team = function (teamname, colour, rss_url, twitter_url, website, coords) {
    this.teamname = teamname;
    this.colour = colour;
    this.rss_url = rss_url;
    this.twitter_url = twitter_url;
    this.website = website;
    this.location = coords;

};

数组本身看起来像:

var teamlist = [32];
teamlist[0] = new    team("Aberdeen","#C01A1A","http://www.football365.com/aberdeen/rss", "https://twitter.com/aberdeenfc","http://www.afc.co.uk/","57�09?33?N�2�05?20?W");
teamlist[1] = new team("Celtic","#C01A1A","http://www.football365.com/aberdeen/rss", "https://twitter.com/aberdeenfc","http://www.afc.co.uk/","57�09?33?N�2�05?20?W");
teamlist[2] = new team("Dundee","#C01A1A","http://www.football365.com/aberdeen/rss", "https://twitter.com/aberdeenfc","http://www.afc.co.uk/","57�09?33?N�2�05?20?W");
teamlist[3] = new team("Dundee United","#C01A1A","http://www.football365.com/aberdeen/rss", "https://twitter.com/aberdeenfc","http://www.afc.co.uk/","57�09?33?N�2�05?20?W");
teamlist[4] = new team("Hamilton Academical","#C01A1A","http://www.football365.com/aberdeen/rss", "https://twitter.com/aberdeenfc","http://www.afc.co.uk/","57�09?33?N�2�05?20?W");
teamlist[5] = new team("Inverness Caledonian Thistle","#C01A1A","http://www.football365.com/aberdeen/rss", "https://twitter.com/aberdeenfc","http://www.afc.co.uk/","57�09?33?N�2�05?20?W");`

我需要能够根据团队名称获取对象的索引。我曾想过一些类似的东西

var a = teamlist.indexOf(teamname: "Aberdeen");

然而,这显然是行不通的。

欢迎任何建议 - 提前感谢! :)

很简单。您可以使用 Array.prototype.some ,将索引声明为词法范围内的变量,并在发生匹配时更改它。然后返回索引。像这样:

var data = [
  {x: '1'},
  {x: '2'},
  {x: '3'},
  {x: '4'}
]; // sample data
function findIndex (num) {
  // num is just the number corresponding to the object
  // in data array that we have to find
  var index = -1; // default value, in case no element is found
  data.some(function (el, i){
    if (el.x === num) {
      index = i;
      return true;
    }
  }); // some will stop iterating the moment we return true
  return index;
}
console.log(findIndex('3'));

希望对您有所帮助!

使用这个简单的按值算法搜索索引。

function index_by_value(teamlist, teamname) {
 index = 0
 for (var i = 0; i < teamlist.length; i++) {
   if (teamlist[i].teamname == teamname) {
    index = i;
   }
 }
    return index;
}
index = index_by_value(teamlist, "Aberdeen"); // an example

但请记住,如果列表中有多个对象具有相同的 teamname,它将返回最后一个对象的索引。如果不存在,该函数将返回 0。

您可以使用过滤方法:

var a = teamlist.filter(function(team) {
    return team.teamname = "Aberdeen";
});

它将生成名为"Aberdeen"的团队对象的新数组。如果你只期望一个团队,你需要从这个数组中获取第一个元素:a[0]

    function getIndex(teamlist, teamname){
        for(var i = 0; i<teamlist.length; i++){
            if(teamlist[i].teamname == teamname){
                return i; // if found index will return
            }
        }
        return -1; // if not found -1 will return
    }
var a = getIndex(teamlist,"Aberdeen"); // will give a as 0

最新更新