gpt4 book ai didi

javascript - 在原型(prototype) Javascript 数组中查找对象的索引

转载 作者:行者123 更新时间:2023-11-29 15:35:32 25 4
gpt4 key购买 nike

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

调用team的对象如下:

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'));

希望对您有所帮助!

关于javascript - 在原型(prototype) Javascript 数组中查找对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com