gogoend / blog

blogs, ideas, etc.
MIT License
9 stars 2 forks source link

Array 方法备忘录 #61

Open gogoend opened 3 years ago

gogoend commented 3 years ago

类方法

Array

静态方法

from

isArray

of

原型方法

对当前数组修改(修改器方法)

copyWithin

fill

pop

弹出尾部元素 并返回该弹出的元素

push

在尾部增加一个或多个元素 返回新的数组长度

reverse

数组逆序 返回逆序后的数组

手写reverse函数
Array.prototype._reverse = function () {
    for (let i = 0; i <= this.length / 2; i++) {
        let temp = this[i]
        this[i] = this[this.length - 1 - i]
        this[this.length - 1 - i] = temp
    }
    return this
}
    
Array.prototype._reverse = function () {
    let i=0,j=this.length-1
    while(i < j){
        [this[i],this[j]] = [this[j],this[i]]
        i++;
        j--;
    }
    return this
}
    

shift

删除头部元素 并返回该删除的元素

sort

数组排序 返回排序后数组

splice

该方法用于对数组中的元素进行增加、删除 接受start作为第一个参数指定要增加、删除元素的位置,接受deleteCount作为第二个参数表示要删除的元素的数量(默认值为Infinity),接受...items作为其它参数表示要在此处添加的元素(默认为空) 返回被删除掉的所有元素

unshift

在头部增加一个或多个元素 返回新的数组长度

返回新数组(且对当前数组不产生副作用)

concat

slice

接受startend参数指定数组读取范围,用于从数组中读取元素 start - 可选,起始索引 - 默认为 0 end - 可选,终止索引 - 默认为 Infinity 返回给定范围内(从起始索引所在元素开始到终止索引所在元素之前)读取到的元素

flat

迭代数组

forEach

手写forEach函数
Array.prototype._forEach = function (cb, thisArg) {
    if(this == null ){
        throw new TypeError('this未定义或为空值')
    }
    if(typeof cb !=="function"){
        throw new TypeError('未传入回调函数')
    }
    let thisO = Object(this)
    for (let i = 0; i < this.length; i++) {
        if(i in thisO){
            cb.call(thisArg,this[i],i,this)
        }
    }
}
    

map

手写map函数
Array.prototype._map = function (cb, thisArg) {
    if(this == null ){
        throw new TypeError('this未定义或为空值')
    }
    if(typeof cb !=="function"){
        throw new TypeError('未传入回调函数')
    }
    let result = []
    let thisO = Object(this)
    for (let i = 0; i < this.length; i++) {
        if(i in thisO){
            result[i] = cb.call(thisArg,this[i],i,thisO)
        }
    }
    return result
}
    

reduce

手写reduce
Array.prototype._reduce = function(cb, initVal) {
    let result = initVal === undefined ? this[0] : initVal;
    for (let i = initVal === undefined ? 1 : 0; i < this.length; i++) {
        result = cb.call(undefined, result, this[i], i, this)
    }
    return result
}

reduceRight

匹配数组内容

includes

数组中是否包含某一元素,第二个参数(可选,默认为0)表示函数开始查找的位置 返回Boolean

indexOf

找到所给定元素(第一个参数)在数组中第一次出现的索引(从前往后找),第二个参数(可选,默认为0)表示函数开始查找的位置 返回值元素所在索引,找不到时返回-1

lastIndexOf

找到所给定元素(第二个参数)在数组中最后一次出现的索引(从后往前找),第二个参数(可选,默认为0)表示函数开始查找的位置 返回值元素所在索引,找不到时返回-1

some

数组中是否包含某一项符合给定条件,第二个参数(可选)接受thisArg为第一个参数绑定this 返回Boolean

every

数组中是否每一项都符合给定条件,第二个参数(可选)接受thisArg为第一个参数绑定this 返回Boolean

filter

筛选数组中符合给定条件的所有元素 第一个参数接受的是一个返回Boolean的函数,第二个参数(可选)接受thisArg为第一个参数绑定this 返回包含所有符合条件元素的数组

find

找到数组中符合给定条件的第一个元素 第一个参数接受的是一个返回Boolean的函数,第二个参数(可选)接受thisArg为第一个参数绑定this 返回值是所找到的符合条件的元素,找不到时返回undefined

findIndex

找到数组中符合给定条件的第一个元素的索引 第一个参数接受的是一个返回Boolean的函数,第二个参数(可选)接受thisArg为第一个参数绑定this 返回值是所找到的符合条件元素的索引,找不到时返回-1

根据数组产生返回其他值

join