js面试题-手写数组的方法

本文主要展示了JavaScript中数组的一些常见方法的实现代码,包括at、concat、every、fill、filter、find、findIndex、flat、forEach、from、includes、indexOf、isArray、join、lastIndexOf、map、of、pop、push、reduce、reverse、shift、slice、some、unshift等。这些方法是JS开发中经常遇到的,了解其工作原理有助于提升编程能力。
摘要由CSDN通过智能技术生成

首先声明,这里只写代码。至于方法的作用请自行查阅mdn文档。

1、Array.prototype.at()方法

Array.prototype.myAt = function(params = 0){
    let temp = this,
        index,
        result,
    if(typeof params == 'string'){
        if(params.length == 0){
            index = 0
        }else{
            if(isNaN(Number(params))){
                index = 0
            }else{
                index = Number(params) == 0 ? 0 : Number(params) > 0 ? Number(params) : temp.length + Number(params)
            }
        }
    }else if(typeof params == 'boolean'){
        index = Number(params)
    }else if(typeof params == 'number'){
        index = params == 0 ? 0 : params > 0 ? params : temp.length + params
    }else if(JSON.stringify(params) == "[]" || JSON.stringify(params) == '{}'){
        index = 0
    }
    for(let i = 0,l = temp.length; i < l; i++){
        if(i == index){
            result = temp[i]
        }
    }
    return result
}

2、Array.prototype.concat方法

Array.prototype.myConcat = function(...params){
    if(params.length == 0)return this
    reutrn [...this,...params].flat()
}

3、Array.prototype.every方法

Array.prototype.myEvery = function(fn,thisValue = window){
    let temp = this
    if(typeof fn != 'function'){
        throw new Error(`${fn} is not a function`)
    }
    for(let i = 0,l = temp.length; i < l; i++){
        if(!fn.call(thisValue,temp[i],i,temp)){
            return false
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值