2017-08-05 7 views
-1

に私は正常配列で最長の単語を検索最長ワード機能を実行します配列のSHORTEST単語を取得します。クリエイティブショートワードのJavaScript

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

うーん... 0より小さい何ですか? –

+0

一番短い単語を取得するのは大丈夫ですか? –

答えて

2

" "よりも小さい全く言葉がないので、あなたのコードが失敗した理由があります。今

var shortestWord = array2[0]; 

スタートは、以降の最初の要素から繰り返します。

for (var i = 1; i < array2.length; i++) { 
    ... 
} 

あなたはそれがないので、私はshortestを削除するために自由を撮影した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);

して繰り返しを減らすので、私はInfinityにこれを好みます必要です。

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);

0

初期化var shortest = 0;var shortest = 100000;のように更新する必要があります。そうでなければ、0より小さいものはありません。ここで100000は非常に大きい値を意味し、単語の長さは確かに長くありません。

0

なぜ2つの変数を作成していますか? 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); 
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