有没有办法将我的 for 循环设置为在将 length 值减 1 之前命中 string[i].length == length
的所有实例?我已经搞乱了添加 while 循环,但我无法安静地得到它。
此脚本旨在根据每个项目的长度从最大到最小对数组进行排序。唯一的问题是我无法弄清楚如何在不跳过已检测到的数组项长度的情况下对其进行排序。
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);
最佳答案
为什么不使用 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
关于javascript - JavaScript for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648909/