作用:查找数组中有没有某一个数据(按照索引正序查找 0 1 2 3 …)
语法:
数组.indexOf(要查找的数据)数组.idnexOf(要查找的数据, 从哪一个索引开始)返回值:是一个数字
如果有你要查找的数字,那么返回的是第一个找到的数据的索引如果没有你要查找的数据,那么返回的是 -1 var arr = ['hello', 'world', '你好', '世界', 'world'] // 表示我要再 arr 这个数组里面查找有没有 'world' 这个数据 var res = arr.indexOf('world') console.log(res) // 1 // 表示我要再 arr 这个数组里面从 索引 2 开始向右查找, 看看有没有 'world' var res = arr.indexOf('world', 2) console.log(res) // 4作用:查找数组中有没有某一个数据(按照索引倒叙查找 9 8 7 6 …)
语法:
数组.lastIndexOf(你要查找的数据)数组.lastIndexOf(你要查找的数据, 从哪一个索引开始)返回值:是一个数字
如果找到你要查找的数据了,那么就返回第一个找到的数据的索引如果没有找到你要查找的数据,那么就返回 -1 var arr = ['hello', 'world', '你好', '世界', 'world'] // 表示从数组的最后开始向前查找, 看看有没有 'world' var res = arr.lastIndexOf('world') console.log(res) // 4 // 表示从索引 3 开始向前查找, 看看数组里面有没有 'world' 这个数据 var res = arr.lastIndexOf('world', 3) console.log(res) // 1作用:就是用来循环遍历数组的,等价于 for 循环遍历数组的地位
语法:
数组.forEach(function (item, index, arr) {})返回值:没有
var arr = ['hello', 'world', '你好', '世界'] // 目前, 数组里面有 4 个成员, 那么这个 function () {} 就执行 4 次 arr.forEach(function (item, index, arr) { // 这个函数, 会根据数组中有多少成员, 就执行多少回 // 第一个形参 item : 数组里面的每一项 // 第二个形参 index : 每一项的索引 // 第三个形参 arr : 表示原始数组 console.log('索引 ' + index + ' 是' + ' --- ' + item) console.log(arr) console.log('函数执行一次完毕') }) /* 上面的注释 : 函数第一次执行的时候 item === 'hello' index === 0 函数第二次执行的时候 item === 'world' index === 1 ... */作用:经过对数组中数据的求和操作,得到一个值
语法:
返回值:是一个值(所有数据的和)
var arr = [1, 2, 3, 4, 5, 6, 7] var res = arr.reduce(function (sum, item, index, arr){ // 返回所有数据的和 return (sum + item) }) console.log(res) // 28