我一点都不明白,有人能解释一下s
是如何有值的吗?
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");
简单地说,
indexOf()
方法返回字符串中指定值第一次出现的位置。
所以当我们做这样的事情时:
s = str.indexOf("o");
我们在str
中找到o
的索引,并将该值赋值回s
。
你可以(也应该)在这里阅读更多关于这个函数的信息。
字符串基本上是一个字符数组,所以当你说时
str = "Hello World"
indexOf函数将其视为
[ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
0 1 2 3 4 5 6 7 8 9 10
所以如果你说str.indexOf('e')
,你会得到第一个e
的索引,它是1。
如果您要查找的字母不存在,函数将返回-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. */