原生JS带你了解数组方法实现及使用

简介: js

序:

巩固基础,可以帮你更好的理解数组的方法,方便项目种使用,其实,最重要的是要准备去面试了,哈哈哈~~

定义一个测试的数组

const FootArr= [
        { name: '小龙虾', num: 999 },
        { name: '榴莲披萨', num: 888 },
        { name: '炸鸡', num: 777 },
        { name: '烤鱼', num: 666 },
        { name: '奶茶', num: 555 }
      ];

1. ForEach

用处:增强for循环,专门用来遍历数组和集合

Array.prototype.forEach = function (callback) {
          for (let i = 0; i < this.length; i++) {
              callback(this[i], i, this)
          }
      }

      FootArr.forEach((item, index) => {
          console.log(item, index)
          // {name: '小龙虾', num: 999} 0
          // {name: '榴莲披萨', num: 888} 1
          // {name: '炸鸡', num: 777} 2
          // {name: '烤鱼', num: 666} 3
          // {name: '奶茶', num: 555} 4
      });

2. Map

用处:map()方法可以创建一个新数组,其结果是该数组中的每一个元素都是调用一个提供的函数后返回的结果。

Array.prototype.map = function (callback) {
          const res = [];
          for (let i = 0; i < this.length; i++) {
              res.push(callback(this[i], i, this))
          }
          return res;
      }

      console.log(FootArr.map((item, index) => `${item.name}--${item.num}--${index}`))
      // ['小龙虾--999--0', '榴莲披萨--888--1', '炸鸡--777--2', '烤鱼--666--3', '奶茶--555--4']

3. Filter

用处:filter()方法会创建一个新数组,原数组的每个元素传入回调函数中,回调函数中有return返回值,多返回值为true,这个元素保存到新数组中,若返回值为false,则该元素不保存到新数组中。原数组不发生改变。

Array.prototype.filter = function (callback) {
          const res = [];
          for (let i = 0; i < this.length; i++) {
              callback(this[i], i, this) && res.push(this[i])
          }
          return res;
      }

      console.log(FootArr.filter(item => item.num == 666));
      // [{name: '烤鱼', num: 666}]

4. Every

用处:every()方法只能遍历数组,符合条件即可跳出循环,返回布尔类型,一项为false就返回false,全为true则返回true。

Array.prototype.every = function (callback) {
          let flag = true;
          for (let i = 0; i < this.length; i++) {
              flag = callback(this[i], i, this)
              if (!flag) break
          }
          return flag;
      }

      console.log(FootArr.every(item => item.num >= 0)); // true
      console.log(FootArr.every(item => item.num >= 1000)); // false

5. Some

用处:some()方法只能遍历数组,符合条件即可跳出循环,返回布尔类型,一项为true就返回true,全为false则返回false。

Array.prototype.some = function (callback) {
          let flag = false;
          for (let i = 0; i < this.length; i++) {
              flag = callback(this[i], i, this)
              if (flag) break
          }
          return flag;
      }

      console.log(FootArr.some(item => item.num == 666)); // true
      console.log(FootArr.some(item => item.num >= 1000)); // false

6. Reduce

用处:reduce()方法接受一个函数作为累加器,reduce为数组中的每一个元素执行一次回调函数,不包括数组中被删除或从未被赋值的元素,接收四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组。

Array.prototype.reduce = function (callback, initValue) {
          let pre = initValue == undefined ? this[0] : initValue;
          let i = initValue == undefined ? 1 : 0;
          for (i; i < this.length; i++) {
              pre = callback(pre, this[i], i, this)
          }
          return pre
      }

      // 计算所有num相加   pre:上一项  next:下一项
      const sum = FootArr.reduce((pre, next) => {
          return pre + next.num
      }, 0)
      console.log(sum); // 3885

7. FindIndex

用处:findIndex()方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。该方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回true是,findindex()返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
  • 如果没有符合条件的元素返回 -1.
Array.prototype.findIndex = function (callback) {
          for (let i = 0; i < this.length; i++) {
              if (callback(this[i], i, this)) {
                  return i
              }
          }
          return -1
      }

      console.log(FootArr.findIndex(item => item.name === '小龙虾')) // 0
      console.log(FootArr.findIndex(item => item.name === '奶茶')) // 4

8. Find

用处:find()方法返回数组中符合测试函数条件的第一个元素

Array.prototype.find = function (callback) {
          for (let i = 0; i < this.length; i++) {
              if (callback(this[i], i, this)) {
                  return this[i]
              }
          }
          return undefined
      }

      console.log(FootArr.find(item => item.name === '小龙虾')) // {name: '小龙虾', num: 999}
      console.log(FootArr.find(item => item.name === '哈根达斯')) // undefined

9. Fill

用处:填充数组

Array.prototype.fill = function (value, start = 0, end) {
          end = (end || this.length - 1) + 1
          for (let i = start; i < end; i++) {
              this[i] = value
          }
          return this
      }

      console.log(FootArr.fill('蛋挞',1 ,2))
      // [
      //   {name: '小龙虾', num: 999},
      //   "蛋挞",
      //   "蛋挞",
      //   {name: '烤鱼', num: 666},
      //   {name: '奶茶', num: 555}
      // ]

      console.log(FootArr.fill({name: '蛋挞', num: 222},1 ,2))
      // [
      //   {name: '小龙虾', num: 999},
      //   {name: '蛋挞', num: 222}
      //   {name: '蛋挞', num: 222}
      //   {name: '烤鱼', num: 666},
      //   {name: '奶茶', num: 555}
      // ]

10. Includes

用处:查找元素,查到返回 true , 反之返回 false ,可查找NaN

Array.prototype.includes = function (value, start = 0) {
          if (start < 0) start = this.length + start
          const isNaN = Number.isNaN(value)
          for (let i = start; i < this.length; i++) {
              // 注意对NAN的判断肯出现两个false的情况,因此要确保两个isNAN都是ture才能任务匹配到NAN
              if (this[i] == value || Number.isNaN(this[i]) && isNaN) {
                // 注意判断NAN的情况,NAN==NAN返回false,因此只能用Number.isNAN去判断
                  return true
              }
          }
          return false
      }

      // 第一个参数是要查找的元素
      // 第二个参数表示搜索的起始位置,默认为 0 。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为 -4 ,但数组长度为 3 ),则会重置为从 0 开始。
      console.log([1, 2, 3].includes(2)) // true
      console.log([1, 2, 3, NaN].includes(NaN)) // true
      console.log([1, 2, 3].includes(1, 1)) // false
      console.log([1, 2, 3].includes(4)) // false

11. Join

用处:将数组用分隔符拼成字符串,分隔符默认为 “,”

Array.prototype.join = function (s = ',') {
          let str = ''
          for(let i = 0; i < this.length; i++) {
              str = i === 0 ? `${str}${this[i]}` : `${str}${s}${this[i]}`
          }
          return str
      }

      console.log([1, 2, 3].join()) // 1,2,3
      console.log([1, 2, 3].join('*')) // 1*2*3

12. Flat

用处:将多维数组转化为单维数组

Array.prototype.flat = function () {
          let arr = this
          while (arr.some(item => Array.isArray(item))) {
              // concat() 方法用于连接两个或多个字符串
              arr = [].concat(...arr)
          }
          return arr
      }

      const testArr = [1, [2, 3, [4, 5]], [8, 9]]
      console.log(testArr.flat()) // [1, 2, 3, 4, 5, 8, 9]
目录
相关文章
|
2月前
|
JavaScript 前端开发
JavaScript 数组方法概览
【5月更文挑战第11天】JavaScript 数组方法概览:push() 添加元素至末尾;pop() 删除并返回最后一个元素;shift() 删除并返回第一个元素;unshift() 向开头添加元素;slice() 返回指定范围的浅拷贝;splice() 删除/替换/添加元素,改变原数组;concat() 合并数组;join() 转换为字符串;reverse() 颠倒顺序;sort() 排序;map() 应用函数并创建新数组;filter() 过滤元素;reduce() 累加元素为单一值。
23 1
|
25天前
|
JavaScript 前端开发 安全
安全开发-JS应用&原生开发&JQuery库&Ajax技术&加密编码库&断点调试&逆向分析&元素属性操作
安全开发-JS应用&原生开发&JQuery库&Ajax技术&加密编码库&断点调试&逆向分析&元素属性操作
|
1月前
|
JavaScript
原生JS实现全选、全不选
原生JS实现全选、全不选
|
14天前
|
JavaScript
js 一键复制到剪贴板(原生js实现)
js 一键复制到剪贴板(原生js实现)
10 0
|
17天前
|
前端开发 JavaScript 容器
程序技术好文:纯原生javascript下拉框表单美化实例教程
程序技术好文:纯原生javascript下拉框表单美化实例教程
|
18天前
|
Web App开发 JavaScript iOS开发
技术笔记:js数组定义和方法(包含ES5新增数组方法)
技术笔记:js数组定义和方法(包含ES5新增数组方法)
|
27天前
|
移动开发 JavaScript 前端开发
原生js如何获取dom元素的自定义属性
原生js如何获取dom元素的自定义属性
23 0
|
27天前
|
JavaScript 前端开发
原生JS如何查询元素属性
原生JS如何查询元素属性
18 0
|
2月前
|
前端开发 JavaScript
前端 js 经典:Object 常用原生方法
前端 js 经典:Object 常用原生方法
68 2
|
2月前
|
前端开发 JavaScript
前端 js 经典:array 原生方法
前端 js 经典:array 原生方法
28 1