gpt4 book ai didi

javascript - 这个循环和返回数据的更好解决方案? Javascript

转载 作者:行者123 更新时间:2023-12-03 16:31:56 25 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.


去年关闭。







Improve this question



convertType(arr) {
let resultArr = arr.map(arr => {
if (arr == '0') {
return 'zero'
}
if (arr == '1') {
return 'one'
}
if (arr == '2') {
return 'two'
}
if (arr == '3') {
return 'three'
}
})
return resultArr;
}
我需要为这个循环找到一个更好的解决方案,以及如何以更好的方式获得这些结果。好吧,总是有一个“开关”循环,但你怎么看?好吗?
这很好用,但我想要更好的解决方案。

最佳答案

我会做一个数组并查找索引:

const numbers = ['zero', 'one', 'two', 'three'];
convertType(arr) {
return arr.map(item => numbers[item]);
}
如果要比较的值不是数组索引或者可能不是所有值都从 0 开始,请使用对象:
const numbers = {
2: 'two',
3: 'three'
somethingElse: 'something else'
};
convertType 的代码相同.

关于javascript - 这个循环和返回数据的更好解决方案? Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65646860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com