1
我試圖用自動生成的值對數組排序,但JS給了我奇怪的結果(console.log給出了[14,2,3,7,9])。我應該添加什麼來獲得[2,3,7,9,14]?排序包含長度值的數組
let text ="Why so serious? Mathematicians shouldn't!";
// clean text
let cleaned_text_1 = text.replace(/[.,?!()]/g,"");
let cleaned_text_2 = cleaned_text_1.replace(/-/g," ");
// split text
let cleaned_text = cleaned_text_2.split(/\s/);
// create the length array
let array_lengths = [];
cleaned_text.forEach(function(d){
array_lengths.push(d.length)
});
// sort the array
sorted_array = array_lengths.sort();
console.log(sorted_array);
'sort'作爲字符串比較。你需要編寫一個比較數字的排序功能。 –
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort –