2013-10-29 265 views
0

有沒有一種方法可以將我的for循環設置爲在將長度值減1之前打到string[i].length == length的所有實例?我在加入while循環時搞砸了,但我無法安靜地得到它。For循環javascript

此腳本旨在根據每個項目的長度從最大到最小排序一個數組。唯一的問題是我不知道如何在不跳過已檢測到的數組項長度的情況下對其進行排序。

var string = ["hello", "world", "fishing", "before", "all", "test"]; 
var length = 0; 
word = 0; 
for (x = 0; x < string.length; x++) { 
if (string[x].length > length) { 
    var length = string[x].length; 
    word = string[x]; 
} 
} 
string1 = []; 
for (i = 0; i < string.length; i++) { 
if (string[i].length == length) { 
    length = string[i].length - 1; 
    string1.push(string[i]); 
    i = 0; 
} 
} 
console.log(string1);  
+0

結果是什麼你想要的? –

回答

2

爲什麼不使用Array.sort()

var string = ["hello", "world", "fishing", "before", "all", "test"]; 

string.sort(function(o1, o2){ 
    return o1.length - o2.length; 
}) 

console.log(string) 

演示:Fiddle

人工分揀:Fiddle