forEach
数组的forEach有三个可选参数,value, index, arr,直接上例子比较容易懂一些,对应值、下标、数组。
并且forEach 没有返回值。我觉得是用来替代for的很好用的方法(因为这样我们就不需要用.length获取数组长度了)
let arr = [1, 2, 3]
let ans = arr.forEach((value, index, arr) => {
console.log(`value = ${value} index = ${index} index = ${arr}`)
//value = 1 index = 0 arr = 1,2,3
//value = 2 index = 1 arr = 1,2,3
//value = 3 index = 2 arr = 1,2,3
})
console.log(ans)
//undefine
当然可以只前两个参数,如(value,index)这样的形式。
map
map有返回值,且map参数与forEach相同,有三个可选参数,value, index, arr,为对应值、下标、数组。
直接上例子比较容易懂一些,
let arr = [1, 2, 3]
let map = arr.map((value, index, arr) => {
console.log(`value = ${value} index = ${index} arr = ${arr}`)
return 2 * value
//value = 1 index = 0 arr = 1,2,3
//value = 2 index = 1 arr = 1,2,3
//value = 3 index = 2 arr = 1,2,3
})
console.log(map)
//[ 2, 4, 6 ]
通过输出可以看到结果,数组从[1, 2, 3]变为[ 2, 4, 6 ],因为我们在return 为 2*value。将所有值乘2后返回,生成新的数组
find
find会返回符合条件的第一个value
let arr = [1, 2, 3]
let find = arr.find(value => {
return value > 1
})
console.log(find)
indexOf
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
这个的用法比较多,如方法确定多个值在数组中的位置等,可查看官方手册
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
此处仅演示一个比较常用的方法
let arr = [1, 2, 3]
let indexOf = arr.indexOf(2)
console.log(indexOf)
//1