任何人都可以帮我简化吗?

时间:2016-12-19 03:55:19

标签: javascript json

var GAME1NUM = "";
if (json.participantIdentities[0].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 0;
} else if (json.participantIdentities[1].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 1;
} else if (json.participantIdentities[2].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 2;
} else if (json.participantIdentities[3].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 3;
} else if (json.participantIdentities[4].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 4;
} else if (json.participantIdentities[5].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 5;
} else if (json.participantIdentities[6].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 6;
} else if (json.participantIdentities[7].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 7;
} else if (json.participantIdentities[8].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 8;
} else if (json.participantIdentities[9].player.summonerName == ACTUALNAME) {
  var GAME1NUM = 9;
}

需要帮助简化代码感觉重复

真的请帮忙,如果你不好,但是如果你可以请男人请

4 个答案:

答案 0 :(得分:2)

使用ES6中的Array#findIndex

var GAME1NUM = json.participantIdentities.findIndex(function(val) {
    return val.player.summonerName === ACTUALNAME;
});

如果您需要更多浏览器兼容性,请使用polyfill

答案 1 :(得分:0)

也许是这样的:



var json = {
  name1 : "name1",
  name2 : "name2"
}

function getName(summonerName){
  return {
    name1 : 1,
    name2 : 2
  }[summonerName]
}

var GAME1NUM = getName(json.name1);
console.log(GAME1NUM);




您创建一个返回对象的函数,您可以使用括号表示法访问对象属性的值。

要在对象中检查的属性作为参数传递给函数。

如果您使用JSON。记得做JSON.parse()

答案 2 :(得分:0)

您可以通过以下方式简化逻辑:

工作演示:



var json = {
  participantIdentities: [
    {"player":{"summonerName":"ACTUALNAME"}},
    {"player":{"summonerName":"ACTUALNAME"}},
    {"player":{"summonerName":"ACTUALNAME"}},
    {"player":{"summonerName":"ACTUALNAME"}},
    {"player":{"summonerName":"ACTUALNAME"}}
  ]
};

var GAME1NUM = 0;
for (var i in json.participantIdentities) {
  if(json.participantIdentities[i].player.summonerName == 'ACTUALNAME') {
    GAME1NUM += 1;
  }
}
console.log(GAME1NUM);




答案 3 :(得分:0)

这是实现它的最简单方法,无需更改源数组

var GAME1NUM = "";

for(var i=0;i<json.participantIdentities.length;i++) {
    if (json.participantIdentities[i].player.summonerName == ACTUALNAME) {
        GAME1NUM = i;
        break;
    }
}