2016-05-03 3 views
-6

私はこれを全く理解していませんが、誰かがsにどのように値があるか説明してください。はいくつかのstr.indexOfアシスタンスのjavascriptを必要とします

var str="Hello World" 

// What is the value of s after each line is executed? 

s = str.indexOf("o"); 

s = str.indexOf("w"); 

s = str.indexOf("r"); 

s = str.lastIndexOf("l"); 
+0

*「誰かがどのように値を持っているか説明してもらえますか?」「indexOf()は値を返し、その値を 's'に割り当てています。それはなぜ/どのように '' sが値を持つのかです。 –

+0

私はあなたの質問に答えましたが、あなたは本当にこのような簡単なことを考え出すために少なくとも*いくつかの努力を払うべきです –

答えて

1

簡単に言えば、

indexOf()方法は、文字列で指定された値の最初の出現位置を返します。私たちは、stroのインデックスを見つけ、sに戻って、その値を代入している

s = str.indexOf("o"); 

は、だから我々はこのような何かをするとき。

read more about the function hereとすることができます。

1

文字列は、基本的には文字の配列であるので、あなたは

str = "Hello World" 

を言うときのindexOf関数は、あなたがstr.indexOf('e')を言うのであれば、あなたが最初のインデックスを取得します

[ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"] 
    0 1 2 3 4 5 6 7 8 9 10 

として扱いますeは1です。

あなたが探している文字が存在しない場合、関数は-1を返します。

+0

答えのシートに「w」が-1と評価されたので、私はその答えをちょうど間違っていると思う。 – spoofskay

+1

大文字と小文字の違いは、 – hampusohlsson

+0

@spoofskayです。ご回答いただければ、それも受け入れてください。 –

1
//The 'indexOf()' method returns an integer value that states the position (startig from 0) of the first occurrence of the value of the parameter passed. 

//Now, 

var str="Hello World" 

s = str.indexOf("o"); 
console.log(s); 
/* This would give an output 4. As you can see, 'o' is the fifth character in the String. If you start from 0, the position is 4. */ 

s = str.indexOf("w"); 
console.log(s); 
/* This would give an output -1. As you can see 'w' doesn't exist in str. If the required value is not found, the function returns -1. */ 

s = str.indexOf("r"); 
console.log(s); 
/* This would give an output 8. Why? Refer to the explanation for the first function. */ 

s = str.lastIndexOf("l"); 
console.log(s); 
/* This would give an output 9. This gives the position of the last occurence of the value of parameter passed. */ 

/* How s has a value? Because the function returns a value that is assigned to s by '=' operator. */ 
関連する問題