Javascript 无法获取数组以正确显示嵌套for循环的结果
我正在尝试完成一个codewars练习,其中您只需根据字符串中的数字按顺序返回一个单词字符串 例如:Javascript 无法获取数组以正确显示嵌套for循环的结果,javascript,arrays,for-loop,nested-loops,Javascript,Arrays,For Loop,Nested Loops,我正在尝试完成一个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"
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
}
功能顺序(字){
let wordsArr=words.split(“”)
让结果=[];
for(设i=0;i
但是,这只返回一个空数组。我的逻辑是,我循环遍历
wordsArr
中每个单词的每个字母,一旦typeof
字母匹配'number'
,然后我将结果的数组索引wordsArr[I][j]
设置为wordsArr[I]
。这不是我期望的工作方式,但是,我不明白为什么 wordsArr[i][j]
是一个字符,不管它是数字还是数字,因此需要检查它是否是数字,这可以通过正则表达式匹配/\d/
来实现。如果是数字,则在结果中添加单词:
功能顺序(字){
let wordsArr=words.split(“”)
让结果=[];
for(设i=0;i console.log(order(“Fo1r pe6ople g3ood th5e the2”)//应该返回“Fo1r the2 g3ood 4of th5e pe6ople”)
更有效的解决方案是使用正则表达式来定位每个单词中的数字字符,然后将剩余的数字转换为实际数字
const a=order(“is2 Thi1s T4est 3a”)
常数b=顺序(“一个好的人的顺序”)
控制台日志(a,b)
功能顺序(字){
返回单词。拆分(“”)
.map(w=>({word:w,n:Number(/\d+/.exec(w)[0]))
.sort((a,b)=>a.n-b.n)
.map(o=>o.word)
}
以下是一种使用简单转换的方法
const stripChars=word=>word.replace(/[A-Za-z]+/g,”)
常量xf=word=>parseInt(stripChars(word),10)
const order=words=>words.split(“”).sort((a,b)=>xf(a)-xf(b)).join(“”)
console.log(
订单('is2 Thi1s T4est 3a'),
)
console.log(
订单('fo1rpe6ople3oodthe2'),
)看起来是使用排序的好例子:
功能顺序(str){
常数r=str.split(/\s+/);
r、 排序((a,b)=>{
设m1=a.match(/\d+/)| |[a],m2=b.match(/\d+/)| |[b];
返回m1[0]>m2[0];
});
返回r;
}
console.log(订单('is2 Thi1s T4est 3a');
控制台日志(订单('Fo1r pe6ople 3ood th5e the2');
log(order('a zebra现在只剩下2个测试3 b')代码>可能是一行中的其他解决方案:
- 分割你的阵列
- 使用
排序(可比较)
重新排序元素
- 将每个单词转换为数组
- 检查是否有数字
- 比较
排序中的这些数字
- 连接单词(数组的元素)
const order=str=>str.split(“”).sort((a,b)=>Array.from(a).find(e=>
e、 match(/\d/)>Array.from(b)。find(e=>e.match(/\d/))?1:-1。join(“”)
控制台日志(订单(“is2 Thi1s T4est 3a”))
console.log(order(“Fo1r pe6ople g3 ood th5e the2”)
wordsArr
是一个字符串,因此split()
的结果将永远不会有number
类型的项。slappy是正确的。尝试将wordsArr[i][j]
包装在Number()
中,如果ApplicatableCodeWars没有让人失望,这应该会将单数字符串字母转换为数字