【发布时间】:2021-07-23 12:35:51
【问题描述】:
我正在编写一个函数来提取单词中包含的单词的索引, 例如:4of Fo1r pe6ople g3ood th5e the2 这应该按顺序排列, 下面是代码,
function order(words){
var result = []
var sorting = words.split(' ').sort()
console.log(sorting);
for(let i=0; i<sorting.length;i++)
{
var temp = sorting[i].split('').sort()//By this the words in the sentence get sorted and i will get the index(number) of the corresponding word at first position.
console.log(temp);
var valueHolder = parseInt(temp) //I will take the above obtained value and convert it into integer
console.log(valueHolder);
result.splice((valueHolder-1),0,sorting[i]) //will pass the index here
}
console.log(result);
}
但我得到了错误的输出:[ 'Fo1r', 'the2', '4of', 'g3ood', 'pe6ople', 'th5e' ]
我错过了什么吗,谁能帮我这个谢谢。
上面的array.splice(index,0,item) 只会在指定位置插入元素,并带有0
预期输出为:[ 'Fo1r', 'the2', 'g3ood', '4of', 'th5e','pe6ople' ]
【问题讨论】:
-
sorting[i].split('').sort()会生成一个字符数组,如果我没有弄错的话,它会存储在temp中。这怎么能用作parseInt的参数?? -
@TostMaster 我有目的地给出,因为 temp 总是给出初始索引值,因为我使用了排序,所以现在所有的数字都对齐了,通过使用 temp,我们将得到默认值作为初始索引项,这样我就可以获得真正的索引然后将其转换为整数
标签: javascript node.js arrays sorting