假设我有以下列表
1: Peter,
2: Mary,
3: Ken
...
我想要一个函数switch
,其返回如下
let value1 = switch("Peter") // return 1
let value2 = switch(3) // return "Ken"
我知道我可以创建一个像这样的愚蠢函数
const switch = (input) => {
if(typeof(input) === string){...}
else if(typeof(input) === number){...}
}
只是想知道是否有任何数据结构可以帮助做得更好,而不是创建用于存储这些对的对象
最佳答案
您可以使用Object.entries
用于同时查找值和键
//cannot assign numbers as keys directly
const data = {
"1": "Peter",
"2": "Mary",
"3": "Ken"
};
//`switch` is a programming language key for `switch/case`
//so I name the function `switchDataInPair` instead of `switch`
function switchDataInPair(input) {
for (const [key, value] of Object.entries(data)) {
//cannot use absolute check with `===`, because numbers are strings
if (key == input) {
return value
}
if (value == input) {
return key
}
}
return "Not defined"
}
console.log(switchDataInPair("Ken")) //3
console.log(switchDataInPair(1)) //"Peter"
console.log(switchDataInPair("Something")) //"Not defined"
关于javascript - 如何正确处理对的数据类型切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71731715/