我正在寻找一些更好的方法来编写这段代码,因为它看起来非常难看。但我想它是正确的,但我只是想知道是否有更好的方法来写这个?基本上,语句中的每个键都需要检查与该键相关的事物。也许我应该写一些大的 if 语句?或者使用一些 JSON 对象并存储密钥名称,以及支票内的名称名称?希望能得到一些关于最好的方法的建议!并且代码不是真正的代码(现在没有),它只是我快速编写的内容,以举例说明真实代码的外观。switch (key) {case 'cat': if (animals.check('kitty')) { delete animalsArray[index]; } break;case 'dog': if (animals.check('doggo')) { delete animalsArray[index]; } break;case 'hippo': if (animals.check('idk')) { delete animalsArray[index]; } break;case 'tiger': if (animals.check('somethingSpecificforTIGER')) { delete animalsArray[index]; } break;case 'toad': if (animals.check('idk')) { delete animalsArray[index]; } break;case 'horse':case 'zebra': if (animals.check('ass')) { delete animalsArray[index]; } break;default: break;}只需要改进代码:P
2 回答

达令说
TA贡献1821条经验 获得超6个赞
使用将键映射到animals.check参数的对象:
const mapping = {
cat: "kitty",
dog: "doggo",
...
};
if (mapping.hasOwnProperty(key) && animals.check(mapping[key])) {
delete animalsArray[index];
}

至尊宝的传说
TA贡献1789条经验 获得超10个赞
我不确定我得到了你想要的东西,但你不能使用类似的东西:
var zoo = {
king : 'lion',
thief : 'snake'
}
var arr = ['lion', 'snake'];
delete arr[arr.indexOf(zoo.king)]
添加回答
举报
0/150
提交
取消