js数组方法整理

js数组的方法很多,了解数组的方法,对于操作数组,就非常简单啦,下面介绍数组的一些常用方法

  • .filter() 过滤
// 此方法是数组的过滤方法,将符合条件的元素返回,返回一个新数组。
const arr = [1, 2, 4, 4, 5, 6, 8]
const newArr = arr.filter(item => item > 2)
console.log(newArr)   // [4, 4, 5, 6, 8]
  • .find() 找出值
// 此方法返回数组中满足条件的第一个元素的值,没有满足条件的,则返回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
  • .findIndex 找出索引
// 此返回数组中满足条件的第一个元素的索引,若没有找到对应元素则返回-1
const arr = [3, 12, 5, 7]
const index = arr.findIndex(item => item > 4)
console.log(index)  // 1
  • Array.from() 可以生成数组,去重
// 此方法从一个类似数组或可迭代对象创建一个新的、浅拷贝的数组实例
// 字符串
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]])![截图](https://upload-images.jianshu.io/upload_images/26198104-1becfe089b7b1b8f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
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]     不会改变原数组
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. join() 功能: 将数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的,默认使用’,'号分...
    樑丶阅读 103评论 0 0
  • 1. 数组有哪些常用方法,功能、返回值、是否会对原数组造成影响? 方法功能返回值改变原数组(Y\N)pop()删除...
    loushumei阅读 203评论 0 0
  • js数组方法整理 整理了以下数组方法 join() push()和pop() shift() 和 unshift(...
    Leson17阅读 199评论 0 0
  • 说点啥 数组是程序员的法宝之一,善用数组方法可以使数据处理变的简单(优雅)。每次重新看数组的知识都有新收获。 什么...
    石菖蒲_xl阅读 940评论 0 11
  • 数组是 js 中最常用到的数据集合,其内置的方法有很多,熟练掌握这些方法,可以有效的提高我们的工作效率,同时对我们...
    魂斗罗小黑阅读 305评论 0 1