我试图根据数组中存在的数字对字符串进行排序,即。 'h2ello f3ere b1ow' 应返回 ['b1ow', 'h2ello' ,' f3ere'] 数组。以下代码适用于两个元素(h2ello 和 b1ow),但当我添加第三个元素时则不然。有谁知道这是为什么吗?
function order(words){
var sentence = [];
words = words.split(" ");
for (var i=0;i<words.length;i++){
for (var m=0;m<words[i].length;m++){
if (!isNaN(parseFloat(words[i][m])) && isFinite(words[i][m])){
var idx = words[i][m];
sentence.splice(idx, 0, words[i]);
}
}
}
console.log(sentence);
}
order('h2ello f3ere b1ow');
最佳答案
最简单的是直接对数组进行排序,而不需要拼接到其他位置未知的位置(在循环中)。
此提案使用 Array#sort
使用回调查找一些小数进行排序。
var array = 'h2ello f3ere b1ow'.split(' ');
array.sort(function (a, b) {
return a.match(/\d+/) - b.match(/\d+/);
});
console.log(array);
关于javascript - 根据字符串中的数字对数组中的字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209936/