gpt4 book ai didi

javascript - 无法获取数组以正确显示嵌套 for 循环的结果

转载 作者:行者123 更新时间:2023-12-03 07:20:15 26 4
gpt4 key购买 nike

我正在尝试完成一个 codewars 练习,在该练习中,您只需根据字符串中的数字按顺序返回一串单词。

例子:

order("is2 Thi1s T4est 3a") // should return "Thi1s is2 3a T4est"
order("4of Fo1r pe6ople g3ood th5e the2") // should return "Fo1r the2 g3ood 4of th5e pe6ople")

这是我目前的尝试:

function order(words) {
let wordsArr = words.split(' ')
let result = [];
for (let i = 0; i < wordsArr.length; i++) {
for (let j = 0; j < wordsArr[i].length; j++) {
if (typeof wordsArr[i][j] === 'number') {
result[wordsArr[i][j]] = wordsArr[i]
}
}
}
return result
}

然而,这只会返回一个空数组。我的逻辑是,我循环遍历 wordsArr 中每个单词的每个字母,一旦 typeof 字母匹配 'number',然后我设置wordsArr[i][j]results 数组索引等于 wordsArr[i]。不过,这并不像我期望的那样有效,我很困惑为什么!

最佳答案

wordsArr[i][j] 是一个字符,不管它是否是数字,所以你需要检查它是否是一个数字,你可以用正则表达式匹配/\d/。如果是数字,则将单词添加到结果中:

function order(words) {
let wordsArr = words.split(' ')
let result = [];
for (let i = 0; i < wordsArr.length; i++) {
for (let j = 0; j < wordsArr[i].length; j++) {
if (wordsArr[i][j].match(/\d/)) {
result[wordsArr[i][j]] = wordsArr[i]
}
}
}
return result.join(' ')
}

console.log(order("is2 Thi1s T4est 3a")) // should return "Thi1s is2 3a T4est"
console.log(order("4of Fo1r pe6ople g3ood th5e the2")) // should return "Fo1r the2 g3ood 4of th5e pe6ople")

关于javascript - 无法获取数组以正确显示嵌套 for 循环的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62565980/

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