1.indexOf
定义:
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
语法:
stringObject.indexOf(searchvalue,fromindex)
参数 | 描述 |
---|---|
searchvalue | 必需。规定需检索的字符串值。 |
fromindex | 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。 |
说明:
该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。
举例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var str = [1,2,3,4,5]
document.write(str.indexOf(2) + '<br>')
document.write(str.indexOf(2,1) + '<br>')
document.write(str.indexOf(2,2) + '<br>')
</script>
</body>
</html>
2. forEach()
定义:
forEach遍历数组获取每一个元素,没有返回值。
语法:
array.forEach(function(currentValue, index, arr), thisValue)
参数:
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | 必需。 数组中每个元素需要调用的函数。 函数参数:
| ||||||||
thisValue | 可选。传递给函数的值一般用 "this" 值。 如果这个参数为空, "undefined" 会传递给 "this" 值 |
举例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button onclick="numbers.forEach(myFunction)">点我</button>
<p id="demo"></p>
<script>
demoP = document.getElementById("demo");
var numbers = [4, 9, 16, 25];
function myFunction(item, index) {
demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>";
}
</script>
</body>
</html>
3. map()
定义:
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
语法:
array.map(function(currentValue,index,arr), thisValue)
参数:
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
| ||||||||
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
举例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var numbers = [4, 9, 16, 25];
numbers.map(v=>{
return document.write(v)
})
</script>
</body>
</html>
4. filter()
定义:
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
语法:
array.filter(function(currentValue,index,arr), thisValue)
参数说明:
参数 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
| ||||||||
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined" |
举例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var arr = [1, 2, 3, 45, 65, 87, 456]
let str = arr.filter(v=>{
return v>=45
})
document.write(str)
</script>
</body>
</html>
5.for