JS原生方法(数组篇)

在实际开发中,或许我们会使用很多JavaScript自带的方法,而且这些方法确实给我们带来了很多便利,大大提高了我们的代码小路,但是,有没有一瞬间,你想知道这些方法到底是怎么实现的呢?接下来我将用几篇博客来进行了解

通过这篇文章可以学到什么呢?

  1. 重新巩固数组各种方法的使用方式
  2. 巩固基础,即便没有这些方法,也能靠基础语法去实现

定义一个测试数组

const StarArr= [
    { name: '科比', num: 24 },
    { name: '詹姆斯', num: 23 },
    { name: '保罗', num: 3 },
    { name: '威少', num: 0 },
    { name: '杜兰特', num: 35 }
]

ForEach

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

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
Array.prototype.forEach = function (callback) {
    for (let i = 0; i < this.length; i++) {
        callback(this[i], i, this)
    }
}

StarArr.forEach((item, index, arr) => {
    console.log(item, index)
})
// { name: '科比', num: 24 } 0
// { name: '詹姆斯', num: 23 } 1
// { name: '保罗', num: 3 } 2
// { name: '威少', num: 0 } 3
// { name: '杜兰特', num: 35 } 4

Map

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

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
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(StarArr.map((item, index) => `${item.name}--${item.num}--${index}`))
// [ '科比--24--0', '詹姆斯--23--1', '保罗--3--2', '威少--0--3', '杜兰特--35--4' ]

Filter

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

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
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(StarArr.filter(item => item.num >= 23))
// [
//     { name: '科比', num: 24 },
//     { name: '詹姆斯', num: 23 },
//     { name: '杜兰特', num: 35 }
// ]

Every

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

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
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(StarArr.every(item => item.num >= 23)) // false
console.log(StarArr.every(item => item.num >= 0)) // true

Some

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

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
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(StarArr.some(item => item.num >= 23)) // true
console.log(StarArr.some(item => item.num >= 50)) // false

Reduce

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

参数代表含义

  • index:遍历项的索引
  • arr:数组本身
  • pre:上一项
  • next:下一项
Array.prototype.reduce = function (callback, initValue) {
    let start = 0
    if (initValue) {
        pre = initValue
    } else {
        pre = this[0]
        start = 1
    }
    for (let i = start; i < this.length; i++) {
        pre = callback(pre, this[i], i, this)
    }
    return pre
}

// 计算所有num相加
const sum = StarArr.reduce((pre, next) => {
    return pre + next.num
}, 0)
console.log(sum) // 85

Findindex

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

  • 当数组中的元素在测试条件时返回true是,findindex()返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
  • 如果没有符合条件的元素返回 -1.

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
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(StarArr.findIndex(item => item.name === '科比')) // 0
console.log(StarArr.findIndex(item => item.name === '姚明')) // -1

Find

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

参数代表含义

  • item:遍历项
  • index:遍历项的索引
  • arr:数组本身
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(StarArr.find(item => item.name === '科比')) // { name: '科比', num: 24 }
console.log(StarArr.find(item => item.name === '姚明')) // undefined

Fill

用处:填充数组

参数代表含义

  • initValue:填充的值
  • start:开始填充索引,默认为0
  • end:结束填充索引,默认长度length -1
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(StarArr.fill('AK、哒哒哒', 1, 3))
// [
//     { name: '科比', num: 24 },
//     'AK、哒哒哒',
//     'AK、哒哒哒',
//     'AK、哒哒哒',
//     { name: '杜兰特', num: 35 }
// ]

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++) {
        if (this[i] === value || Number.isNaN(this[i]) === isNaN) {
            return true
        }
    }
    return false
}

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

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

Flat

Array.prototype.flat = function () {
    let arr = this
    while (arr.some(item => Array.isArray(item))) {
        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]

JS原生其他方法

JS原生(数组篇)
JS原生(Object篇、Function篇)

结束语

如果你觉得此文对你有一丁点帮助,点个赞,鼓励一下阿磊哈哈。

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值