array.find
find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
另请参见 findIndex() 方法,它返回数组中找到的元素的索引,而不是其值。
如果需要找到一个元素的位置或者一个元素是否存在于数组中,使用array.prototype.indexOf()或 Array.prototype.includes()。
语法
arr.find(callback[, thisArg])
参数
callback 在数组每一项上执行的函数,接收3个参数:
element 当前遍历到的元素
index 当前遍历到的索引
array 数组本身
thisArg 可选,指定 callback的this参数
返回值
当某个元素通过callback的测试时,返回数组中的一个值,否则返回 undefined 。
描述
find 方法对数组中的每一项元素执行一次 callback 函数,直至有一个callback返回true。当找到这样一个元素后,该方法会立即返回这个元素的值,否则返回undefined。注意callback函数会为数组中的每个索引调用从0到length-1,而不仅仅是那些被赋值的索引,这意味着对于稀疏数组来说,该方法的效率要低于那些只遍历有值的索引的方法。
Math.sqrt() 开平方
findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
语法
arr.findIndex(callback[, thisArg])
array.forEach
forEach() 方法对数组的每个元素执行一次提供的函数.
var a = ['a','b','c']
a.forEach(function(element) {
console.log(element);
})
// a
// b
// c
语法
arr.forEach(function callback(currentValue,index,array){
// your iterator
}[, thisArg]);
Array.from() 方法从一个类似数组或可迭代对象中创建一个新的数组实例
语法
Array.from(arrayLike[, mapFn[, thisArg]])
参数
arrayLike 想要转换成数组的伪数组对象或可迭代对象。
mapFn(可选参数) 如果指定了该参数,新数组中的每个元素会执行该回调函数。
thisArg(可选参数) 可选参数,执行回调函数 mapFn 时 this 对象
返回值
一个新的数组实例
示例
从字符串获得数组
Array.from('foo');
// ['f','o','o']
从集合中获得数组
var s = new Set(['foo',window]);
Array.from(s);
// ['foo',window]
从映射中获得数组
var m = new Map([[1,2],[2,4],[4,8]]);
Array.from(m);
// [[1,2],[2,4],[4,8]]
从一个类似数组的对象中获得数组(其作为array构造时的参数)
function f() {
return Array.from(arguments);
}
f(1,2,3);
// [1,2,3]
使用箭头函数和 Array.from
Array.from([1,2,3], x=>x+x);
//[2,4,6]
Array.from({length:5},(v,i)=>i);
// [0,1,2,3,4]