我想按降序排列數組,然後返回該數組的前20個元素。下面的代碼被設計爲這樣做,但是,問題出現時,調用[].slice.call(topwords).sort(function(a, b){ return b - a});
時,數組沒有按降序排列。當通過node-debug
運行的代碼,我可以看到,topwords填充,並填充爲這樣:如何排序和處理數組
"": 19
0-0: 1
1-0: 2
1-0.: 1
1-1: 1
2: 1
2/3: 1
2pm: 1
3-0: 3
3-1: 1
4: 1
4-0: 2
11am: 1
15: 1
16: 1
19:45: 1
28: 1
30: 1
30%: 2
// more of the same ...
我不清楚爲什麼這個陣列不能排序,然後整個元素推到toptwenty要顯示?
CODE:
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
changedString = string.replace(/,/g, " "), // remove the array elements
split = changedString.split(" "), // split the string
words = []; // array for the words
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
// function for returning the top 20 words from getFreqword()
function getTopwords(){
var topwords = getFreqword(),
toptwenty = [];
[].slice.call(topwords).sort(function(a, b){
return b - a
});
if (topwords.length < 20){
topwords = toptwenty;
return toptwenty;
} else {
for (var i=0; i<20; i++){
toptwenty.push(topwords[i]); // push the first 20 elements in topusers to the topten array
}
return toptwenty;
}
}
編輯:
[ undefined,
undefined,
1,
undefined,
1,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
1,
1,
undefined,
undefined,
undefined ]
運行代碼時返回的值。
嘗試反過來:'words.sort(...)切片(...) ' – georg
'sort(function(a,b){ return b - a })'只適用於數字,沒有別的! – Bergi
[不要將數組用於'words'](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/)! – Bergi