Javascript 需要一些str.indexOf帮助吗
我完全不明白这一点,有人能解释一下Javascript 需要一些str.indexOf帮助吗,javascript,html,Javascript,Html,我完全不明白这一点,有人能解释一下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
是如何有价值的吗
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。“请有人解释s是如何具有值的”嗯,
indexOf()
返回一个值,并且您正在将该值分配给s
。这就是为什么“s
有一个值”的原因。我已经回答了你下面的问题,但你真的应该自己至少花点精力来弄清楚这样简单的事情谢谢,我只是感到困惑,因为我的答题纸上说“w”的值为-1,我想这只是答案上的一个错误。注意大写和小写之间有区别letters@spoofskay,如果你得到了回答,那么也请接受。
//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. */