我有这个数组,怎样才能避免else语句发生在数组中的数量
SoftwareBadges =
[
{ Title: "Playtech", Guid: "7e9", xPos: "96" },
{ Title: "BetSoft", Guid: "890", xPos: "169" },
{ Title: "WagerWorks", Guid: "35c", xPos: "242" },
{ Title: "Rival", Guid: "c35", xPos: "314" },
{ Title: "NetEnt", Guid: "59e", xPos: "387" },
{ Title: "MicroGaming", Guid: "19a", xPos: "460" },
{ Title: "Cayetano", Guid: "155", xPos: "533" },
{ Title: "OpenBet", Guid: "cfe", xPos: "607" },
{ Title: "RTG", Guid: "4e6", xPos: "680" },
{ Title: "Cryptologic", Guid: "05d", xPos: "753" },
{ Title: "CTXM", Guid: "51d", xPos: "827" },
{ Title: "Sheriff", Guid: "63e", xPos: "898" },
{ Title: "Vegas Tech", Guid: "a50", xPos: "975" },
{ Title: "Top Game", Guid: "0d0", xPos: "1048" },
{ Title: "Party Gaming", Guid: "46d", xPos: "1121" }
];
for (var s in SoftwareBadges) {
if (SoftwareBadges[s]["Guid"] == "7e9"){
alert(SoftwareBadges[s]["Title"]);
}
else{alert('fdsfsdf');}
}
答案 0 :(得分:1)
使用Array.find()。它返回满足回调条件的第一个元素,并将停止迭代其余元素。
SoftwareBadges =
[
{ Title: "Playtech", Guid: "7e9", xPos: "96" },
{ Title: "BetSoft", Guid: "890", xPos: "169" },
{ Title: "WagerWorks", Guid: "35c", xPos: "242" },
{ Title: "Rival", Guid: "c35", xPos: "314" },
{ Title: "NetEnt", Guid: "59e", xPos: "387" },
{ Title: "MicroGaming", Guid: "19a", xPos: "460" },
{ Title: "Cayetano", Guid: "155", xPos: "533" },
{ Title: "OpenBet", Guid: "cfe", xPos: "607" },
{ Title: "RTG", Guid: "4e6", xPos: "680" },
{ Title: "Cryptologic", Guid: "05d", xPos: "753" },
{ Title: "CTXM", Guid: "51d", xPos: "827" },
{ Title: "Sheriff", Guid: "63e", xPos: "898" },
{ Title: "Vegas Tech", Guid: "a50", xPos: "975" },
{ Title: "Top Game", Guid: "0d0", xPos: "1048" },
{ Title: "Party Gaming", Guid: "46d", xPos: "1121" }
];
let foundBadge = SoftwareBadges.find(badge => badge.Guid === '7e9');
console.log(foundBadge ? foundBadge : 'asdfads');
答案 1 :(得分:0)
我猜你只想发一次警报,是吗?要做到这一点,你需要另一个变量,如:
SoftwareBadges =
[
{ Title: "Playtech", Guid: "7e9", xPos: "96" },
{ Title: "BetSoft", Guid: "890", xPos: "169" },
{ Title: "WagerWorks", Guid: "35c", xPos: "242" },
{ Title: "Rival", Guid: "c35", xPos: "314" },
{ Title: "NetEnt", Guid: "59e", xPos: "387" },
{ Title: "MicroGaming", Guid: "19a", xPos: "460" },
{ Title: "Cayetano", Guid: "155", xPos: "533" },
{ Title: "OpenBet", Guid: "cfe", xPos: "607" },
{ Title: "RTG", Guid: "4e6", xPos: "680" },
{ Title: "Cryptologic", Guid: "05d", xPos: "753" },
{ Title: "CTXM", Guid: "51d", xPos: "827" },
{ Title: "Sheriff", Guid: "63e", xPos: "898" },
{ Title: "Vegas Tech", Guid: "a50", xPos: "975" },
{ Title: "Top Game", Guid: "0d0", xPos: "1048" },
{ Title: "Party Gaming", Guid: "46d", xPos: "1121" }
];
var enteredInElse = false;
for (var s in SoftwareBadges) {
if (SoftwareBadges[s]["Guid"] == "7e9"){
alert(SoftwareBadges[s]["Title"]);
} else{ enteredInElse = true }
}
if(enteredInElse){
alert('fdsfsdf');
}