这是我的 JavaScript 数组:
var champions = {
"Aatrox":["Blood Well","Dark Flight", "No Q2", "Blood Thirst", "Blood Price", "Blades of Torment", "No E2", "Massacre"],
"Ahri":["Essence Theft","Orb of Deception", "Fox-Fire", "Charm", "Spirit Rush"],
"Akali":["Twin Disciplines", "Mark of the Assassin", "Twilight Shroud", "Crescent Slash", "Shadow Dance"],
"Alistar":["Trample","Pulverize","Headbutt","Triumphant Roar","Unbreakable Will"],
"Amumu":["Cursed Touch","Bandage Toss","Despair","Tantrum","Curse of the Sad Mummy"]
};
现在我从 PHP 表单中获取一个带有冠军名称的变量,例如Akali
并且还有一个咒语名称,例如Twin Disciplines
现在我想检查该咒语和冠军是否存在于我的数组中,如果存在,则位于哪个位置:
var championName = echo $champion;
var Spell = echo $championSpells[1][$j];
if($.inArray(championName, champions)==-1){
var existsInArray = false;
} else{
var existsInArray = true;
}
此时我真的很困惑 Spell is = 'Twin Disciplnes' ChampionName is = 'Akali' 所以通过这些例子我想检索 1 如果它是例如 'Mark of the Assassin' 我想检索 2因为它是第二个。
最佳答案
在Javascript中你可以使用Array.prototype.indexOf()
用于搜索数组中的项目。结果是以 0
开头的索引。如果未找到,则返回 -1
。
var champions = {
"Aatrox": ["Blood Well", "Dark Flight", "No Q2", "Blood Thirst", "Blood Price", "Blades of Torment", "No E2", "Massacre"],
"Ahri": ["Essence Theft", "Orb of Deception", "Fox-Fire", "Charm", "Spirit Rush"],
"Akali": ["Twin Disciplines", "Mark of the Assassin", "Twilight Shroud", "Crescent Slash", "Shadow Dance"],
"Alistar": ["Trample", "Pulverize", "Headbutt", "Triumphant Roar", "Unbreakable Will"],
"Amumu": ["Cursed Touch", "Bandage Toss", "Despair", "Tantrum", "Curse of the Sad Mummy"]
};
function getPos(o,n, s) {
return n in o && o[n].indexOf(s);
}
document.write(getPos(champions, 'Akali', 'Twin Disciplines') + '<br>');
document.write(getPos(champions, 'Akali', 'Mark of the Assassin') + '<br>');
关于javascript - 检查 javascript 数组中变量的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34595613/