我成功运行了最长的单词函数,用于搜索数组中最长的单词:
var array = ["dog", "cat", "horse"];
var largest = 0;
var longestWord = " ";
for (var i = 0; i < array.length; i++) {
if (array[i].length <= largest) {
largest = array[i].length;
longestWord = array[i];
}
}
console.log("The longest word is "+ longestWord);
console.log("The length of the word is " + largest);
试图有点聪明,我潜入并试图反转条件运算符以获得数组中的SHORTEST字:
var array2 = ["dog", "cat", "horse", "hsalsaaaaa"];
var shortest = 0;
var shortestWord = " ";
for (var i = 0; i < array2.length; i++) {
if (array2[i].length < shortest) { // if an item length is less than 0 then
shortest = array2[i].length; // shortest is equal to the length of the item
shortestWord = array2[i]; // then " " will be the item itself;
}
}
console.log("The shortest word is "+ shortestWord);
console.log("The length of the word is " + shortest);
但是这段代码一直向我发送0和空白字。知道在这里调整一下吗?
谢谢!
答案 0 :(得分:2)
您的代码失败的原因是因为没有小于" "
的单词。
从
开始var shortestWord = array2[0];
现在,从第一个元素开始迭代。
for (var i = 1; i < array2.length; i++) {
...
}
我更喜欢Infinity
,因为您将迭代次数减少了1次。
var array2 = ["dog", "cat", "horse", "hsalsaaaaa"];
var shortestWord = array2[0];
for (var i = 1; i < array2.length; i++) {
if (array2[i].length < shortestWord.length) { // if an item length is less than 0 then
shortestWord = array2[i]; // then " " will be the item itself;
}
}
console.log("The shortest word is "+ shortestWord);
console.log("The length of the word is " + shortestWord.length);
&#13;
我已经冒昧地删除shortest
,因为它不是必需的。
答案 1 :(得分:1)
您可以使用起始值而不是零Infinity
,这是最大可能值。
var array2 = ["dog", "cat", "horse", "hsalsaaaaa"],
shortest = Infinity,
shortestWord,
i
for (i = 0; i < array2.length; i++) {
if (array2[i].length < shortest) { // if an item length is less than 0 then
shortest = array2[i].length; // shortest is equal to the length of the item
shortestWord = array2[i]; // then " " will be the item itself;
}
}
console.log("The shortest word is " + shortestWord);
console.log("The length of the word is " + shortest);
答案 2 :(得分:0)
您需要将初始化var shortest = 0;
更新为var shortest = 100000;
之类的内容。否则任何东西都不会小于0.这里100000表示任何非常大的值,并且单词的长度肯定不会那么大。
答案 3 :(得分:0)
为什么要创建两个变量? shortestWord
就够了:
var arr = ["dog", "cat", "horse", "hsalsaaaaa"];
var shortestWord = arr[0]
for (var i = 0; i < arr.length; i++)
if(arr[i].length < shortestWord.length) shortestWord = arr[i];
console.log("The shortest word is", shortestWord, ",length is", shortestWord.length);
答案 4 :(得分:0)
var array2 = ["dog", "cat", "horse", "hsalsaaaaa"];
var shortest = 0;
var shortestWord = " ";
for (var i = 0; i < array2.length; i++) {
if (array2[i].length <= shortest) {
shortest = array2[i].length;
shortestWord = array2[i];
}
}
console.log("The shortest word is "+ shortestWord);
console.log("The length of the word is " + shortest);
That was because your if condition was wrong