js数组的方法很多,了解数组的方法,对于操作数组,就非常简单啦,下面介绍数组的一些常用方法
// 此方法是数组的过滤方法,将符合条件的元素返回,返回一个新数组。
const arr = [1, 2, 4, 4, 5, 6, 8]
const newArr = arr.filter(item => item > 2)
console.log(newArr) // [4, 4, 5, 6, 8]
// 此方法返回数组中满足条件的第一个元素的值,没有满足条件的,则返回undefined。
const arr = [5, 12, 13, 9]
const found = arr.find(item => item > 12)
console.log(found) // 13
const found1 = arr.find(item => item > 100)
console.log(found) // undefined
// 此返回数组中满足条件的第一个元素的索引,若没有找到对应元素则返回-1
const arr = [3, 12, 5, 7]
const index = arr.findIndex(item => item > 4)
console.log(index) // 1
// 此方法从一个类似数组或可迭代对象创建一个新的、浅拷贝的数组实例
// 字符串
console.log(Array.from('foo')) // ['f', 'o', 'o']
// 用set生成数组,这个还可以数组去重
const set = new Set(['foo', 'bar', 'baz', 'foo'])
console.log(Array.from(set)) // ['foo', 'bar', 'baz']
// 用Map生成数组,new Map之后,会变成一个简直对的对象
const map = new Map([[1, 2], [2, 4], [4, 8]])
console.log(Array.from(map)) // [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
console.log(Array.from(mapper.values()) // ['a', 'b']
console.log(Array.from(mapper.keys()); // ['1', '2']
// 从类数组对象(arguments)生成数组
function f() {
return Array.from(arguments)
}
console.log(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]
Array.from({length: 3}, (v, i) => 1); // [1, 1, 1]
- forEach() 遍历数组方法, 不是数组会报错,一定要是数组,空数组也行
const arr = [1, 2, 3];
arr.forEach((item => {
console.log(item);
}
// 1
// 2
// 3
- .map()方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
const arr = [1, 2, 4, 3, 7]
const map = arr.map((item) => {
return item * 2
}
console.log(map) // [2, 4, 8, 6, 14] 不会改变原数组