Bir diziyi azalan sırada sıralamaya çalışıyorum ve daha sonra bu dizinin ilk 20 öğesini döndürmeye çalışıyorum. Ancak, aşağıdaki kod, bunu yapmak için tasarlanmıştır, sorun, [].slice.call(topwords).sort(function(a, b){ return b - a});
çağrıldığında dizinin azalan düzende sıralanmadığı ortaya çıkar. node-debug
içinden kod çalıştırırken ben topwords doldurulur, ve bu şekilde doldurulur görebiliriz:Bir dizi nasıl sıralanır ve işlenir
"": 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 ...
bu dizi sıralanabilir edilemez ve daha sonra elemanın tüm toptwenty itildi yüzden ben emin değilim görüntülenecek?
KODU:
// 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;
}
}
DÜZENLEME: kodu çalıştırırken döndürülür Ne
[ undefined,
undefined,
1,
undefined,
1,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
1,
1,
undefined,
undefined,
undefined ]
.
bunu tersi deneyin: Eğer bir yedek tutmak istiyorsanız, böyle bir şey deneyebilirsiniz. 'Words.sort (...) dilim (...) ' – georg
' sort (işlev (a, b) { döndürme b - a }) 'yalnızca sayılarla çalışır, başka bir şey yok! – Bergi
[Sözler için bir dizi kullanmayın] (http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/)! – Bergi