需要一些str.indexOf帮助javascript
need some str.indexOf assistance javascript
我一点都不明白,有人能解释一下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. */
相关文章:
- 需要帮助设置json数组
- JQuery需要帮助理解(i,el)
- 如何在输入字段中的按钮的帮助下打开日历,该字段的类型为“=”;日期”;
- 需要帮助谷歌地图方向面板在FancyBox中显示
- 我需要为我的朋友在这个项目上提供帮助
- 使用密码对话框Javascript请求帮助
- 为什么indexOf在这个js代码中不起作用
- JavaScript计算帮助(乘以时间)
- 另一个if(!$scope.$$phase)$scope$apply()szenario-需要帮助才能通关
- Angularjs通过过滤器获取indexOf
- indexOf具有2个参数
- Angular ng类需要帮助设置
- {{#each}}内部的Handlebar帮助程序
- .indexOf()不适用于特定元音
- php帮助-需要使用字符串回显php
- JavaScript,JQuery.需要帮助才能获得'name'从我的JSON中删除
- jQuery基于下拉选择更新帮助文本
- 需要比特币校验地址和json帮助
- 在JavaScript中处理数组和对象时需要帮助
- 需要一些str.indexOf帮助javascript