我有一个空数组,如下所示:
var itemsWithEmptySockets = [];
可能会填充以下一个或多个值(取决于通过n API获取的信息):
0, 1, 2, 4, 5, 6, 7, 8, 9, 15, 16
哪里:
0 = Head
1 = Neck
2 = Shoulder
4 = Chest
5 = Waist
6 = Legs
7 = Feet
8 = Wrist
9 = Hands
14 = Back
15 = MainHand
16 = SecondaryHand
我想测试一下数组中包含的内容,并通过将字符串存储在数组中将这些数字实质上转换为字符串,例如如果为0,则Head的套接字为空,将“ Head”添加到新数组中,然后我想使用该数组在DOM中将“ Head”显示为字符串。
为了这样做,我尝试了一个switch语句,例如
switch(itemsWithEmptySockets){
case 0:
emptyItems.push("Head");
break;
但是似乎switch语句不支持以这种方式使用数组,即传递数组
itemsWithEmptySockets
。有没有比12 if语句更有效的方法呢?例如
for(i=0; i < itemsWithEmptySockets.length; i++){
if(itemsWithEmptySockets[i] == 0){
emptyItems.push("Head");
}
if(itemsWithEmptySockets[i] == 1){
emptyItems.push("Neck");
}
etc.
}
非常感谢您的帮助!
最佳答案
我认为我不会使用switch
。我会使用一个映射对象:
// In one central place
var socketMappings = {
0: "Head",
1: "Neck",
2: "Shoulder",
4: "Chest",
5: "Waist",
6: "Legs",
7: "Feet",
8: "Wrist",
9: "Hands",
14: "Back",
15: "MainHand",
16: "SecondaryHand"
};
// Where you're doing this
var emptyItems = [];
itemsWithEmptySockets.forEach(function(entry) {
emptyItems.push(socketMappings[entry]);
});
现场示例:
// In one central place
var socketMappings = {
0: "Head",
1: "Neck",
2: "Shoulder",
4: "Chest",
5: "Waist",
6: "Legs",
7: "Feet",
8: "Wrist",
9: "Hands",
14: "Back",
15: "MainHand",
16: "SecondaryHand"
};
// Where you're doing this
itemsWithEmptySockets = [
0,
14,
5
];
var emptyItems = [];
itemsWithEmptySockets.forEach(function(entry) {
emptyItems.push(socketMappings[entry]);
});
// Show result
snippet.log(itemsWithEmptySockets.join(", "));
snippet.log(emptyItems.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
或者,如果
emptyItems
中没有任何其他内容,请使用Array#map
:// In one central place
var socketMappings = {
0: "Head",
1: "Neck",
2: "Shoulder",
4: "Chest",
5: "Waist",
6: "Legs",
7: "Feet",
8: "Wrist",
9: "Hands",
14: "Back",
15: "MainHand",
16: "SecondaryHand"
};
// Where you're doing this
var emptyItems = itemsWithEmptySockets.map(function(entry) {
return socketMappings[entry];
});
现场示例:
// In one central place
var socketMappings = {
0: "Head",
1: "Neck",
2: "Shoulder",
4: "Chest",
5: "Waist",
6: "Legs",
7: "Feet",
8: "Wrist",
9: "Hands",
14: "Back",
15: "MainHand",
16: "SecondaryHand"
};
// Where you're doing this
itemsWithEmptySockets = [
0,
14,
5
];
// Where you're doing this
var emptyItems = itemsWithEmptySockets.map(function(entry) {
return socketMappings[entry];
});
// Show result
snippet.log(itemsWithEmptySockets.join(", "));
snippet.log(emptyItems.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript - 如何在JavaScript中的数组上切换()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30305077/