Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 需要一些str.indexOf帮助吗_Javascript_Html - Fatal编程技术网

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. */