我根本不明白这一点,有人可以解释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");
答案 0 :(得分:1)
简单地说,
indexOf()
方法返回字符串中第一次出现指定值的位置。
所以当我们做这样的事情时:
s = str.indexOf("o");
我们在o
中找到了str
的索引,并将该值重新分配到s
。
你可以(而且应该)read more about the function here。
答案 1 :(得分:1)
字符串基本上是一个字符数组,所以当你说
时override class func shouldIncludeInDefaultSchema() -> Bool {
return false
}
indexOf函数将其视为
str = "Hello World"
因此,如果您说[ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
0 1 2 3 4 5 6 7 8 9 10
,您将获得第一个str.indexOf('e')
的索引,即1。
如果您要查找的字母不存在,该函数将返回-1。
答案 2 :(得分: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. */