JS数组中的方法以及对应的Polyfill

/**
 * copyWithin(): 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
 * entries(): 方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
 * Array.prototype.fill() : 用一个固定值填充一个数组中从起始索引到终止索引内的全部元素,arr.fill(value[, start[, end]])
 * Array.prototype.find() : 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
 * Array.prototype.findIndex() : 方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
 * Array.prototype.flat() : 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
 * Array.prototype.flatMap() : 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为1的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。
 * Array.prototype.keys() : 返回一个包含数组中每个索引键的Array Iterator对象
 * Array.prototype.values() : 返回一个包含数组中每个索引键的Array Iterator对象
 * lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始
 */

/** 1、Array.isArray() */
    Array.isArray([1,2]) // true
    Array.isArray(Array.prototype);// 鲜为人知的事实:其实 Array.prototype 也是一个数组。

    /** Polyfill */
    Array.isArray = function(arg){
        return Object.prototype.toString.call(arg) === '[Obejct Array]';
    }

/** 2、Array.form() : 从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例 */
    Array.from('abcd');// ['a', 'b', 'c', 'd']                         ---- 新数组
    Array.from(new Set(['a', 'b', 'c', 'd'])); // ['a', 'b', 'c', 'd'] ---- 从Set中 新数组
    Array.from(new Map([[1,2], [3,4]])); // [[1,2], [3,4]]             ---- 从Map中 新数组
    function fun() {
        return Array.from(arguments); // fun(1,2,3);// [1,2,3]         ---- 从数组对象中
    }
    Array.from(new Set([1,2,2,3,1,3])); // 【1,2,3】                   ----- 数组去重

    /** Polyfill */ // 情况有点多 MDN

/** 3、 Array.of() : 变量变数组*/
    Array.of(1, 2, 3, 'str', '5'); // [1,2,3,'str','5']
    /** Polyfill */
    Array.of = function() {
        return Array.prototype.slice.call(arguments);
    };

/** 4、 Array.prototype.concat() : 合并(连接)两个或多个数组,返回新数组,不修改现有数组   !!!:浅拷贝  */
    let arr1 = ['a', 'b', 'c'], arr2 = ['d', 'e', 'f'];
    console.log(arr1.concat(arr2)); // ["a", "b", "c", "d", "e", "f"]

    /** Polyfill */

/** 5、 Array.prototype.every() :  测试一个数组内的所有元素是否能通过指定函数的逻辑,返回Boolean*/
    let arr = [1, 2, 3, 4, 5];
    console.log(arr.every((item, index, array) => { return item > 0; })); // true

    /** Polyfill */
    Array.prototype.every = function (callback) {
        let res = true;
        for (let i = 0; i < this.length; i++) {
            if(!callback(this[i], i, this)) res = false;
        }
        return res;
    }

/** 6、 Array.prototype.some() :  测试数组中是不是至少有1个元素通过了被提供的函数测试,返回Boolean*/
    let arr = [1, 2, 3, 4, 5];
    console.log(arr.some((item, index, array) => { return item > 4; })); // true

    /** Polyfill */
    Array.prototype.some = function (callback) {
        let res = false;
        for (let i = 0; i < this.length; i++) {
            if(callback(this[i], i, this)) res = true;
        }
        return res;
    }

/** 7、 Array.prototype.filter() : 返回一个新数组, 其包含通过所提供函数实现的测试的所有元素   !!!:浅拷贝  */
    let arr = [1, 2, 3, 5];
    console.log(arr.filter((item, index, array)=>{ return item > 0; }));

    /** Polyfill */
    Array.prototype.filter = function (callback) {
        let res = [], index = 0;
        for (let i = 0; i < this.length; i++) {
            if(callback(this[i], i, this)){
                res[index] = this[i];
                index++;
            }
        }
        return res;
    }

/** 8、 Array.prototype.forEach() : 方法对数组的每个元素执行一次提供的函数。 */
    let arr = [1, 2, 3, 5];
    arr.forEach((item, index, array)=>{ console.log(item) })
    // !!!: 没有办法中止或者跳出 forEach() 循环,除了抛出一个异常。
    // !!!: callback 如果数组在迭代时被修改了,则其他元素会被跳过。不能在循环内使用 删除或者添加操作

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

/** 9、 Array.prototype.includes() : 方法用来判断一个数组是否包含一个指定的值 arr.includes(value, index) */
    [1, 2, 3].includes(2);     // true
    [1, 2, 3].includes(3, 3);  // false
    [1, 2, 3].includes(3, -1); // true
    [1, 2, NaN].includes(NaN); // true

/** 10、 Array.prototype.indexOf() : 方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1 */
    // 
    /** Polyfill */
    // 循环返回下标,如果没有,返回-1

/** 11、 Array.prototype.join() : 将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符 */
    let arr = ['Fire', 'Air', 'Water'];
    console.log(elements.join()); // "Fire,Air,Water"    // 如果缺省该值,数组元素用逗号(,)分隔
    console.log(elements.join('')); // "FireAirWater"
    console.log(elements.join('-')); // "Fire-Air-Water"

/** 12、 Array.prototype.map() : 返回一个新数组,该数组中的每个元素都调用一个提供的函数后返回的结果  !!!: 浅拷贝 */
    // map 不修改调用它的原数组本身(当然可以在 callback 执行时改变原数组)
    var numbers = [1, 4, 9];
    var roots = numbers.map(Math.sqrt);
    // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
    // arr.map(callback(item, index, arr))

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

/** 13、 Array.prototype.pop() : 从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度 */
    let myFish = ["angel", "clown", "mandarin", "surgeon"];
    let popped = myFish.pop();
    console.log(myFish); // ["angel", "clown", "mandarin"]
    console.log(popped); // surgeon
/** 14、 Array.prototype.shift() : 从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度 */


/** 15、 Array.prototype.push() : 将一个或多个元素添加到数组的末尾,并返回该数组的新长度 */
    // 合并两个数组,  使用 apply() 添加第二个数组的所有元素
    var vegetables = ['parsnip', 'potato'];
    var moreVegs = ['celery', 'beetroot'];
    // 将第二个数组融合进第一个数组
    // 相当于 vegetables.push('celery', 'beetroot');
    Array.prototype.push.apply(vegetables, moreVegs);
    console.log(vegetables); 
    // ['parsnip', 'potato', 'celery', 'beetroot']

    /** Polyfill */
    Array.prototype.push = function () {
        for (let i = 0; i < arguments.length; i++) {
            this[this.length] = arguments[i] 
        }
        return this.length;
    }

/** 16、 Array.prototype.unshift() : 将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组 */

    /** Polyfill */
    Array.prototype.unshift = function () {
        ///定义一个数组保存当前数组的值和newUnShift方法传递进来的参数
        var newArr = [];
        //循环newUnShift方法传递进来的参数并保存到newArr中
        for(var i=0;i<arguments.length;i++){
            newArr[i] = arguments[i];
        }
        var len = newArr.length;
        //循环当前要添加数组 也保存在newArr中
        for(var j=0;j<this.length;j++){
            newArr[ parseInt(len+j) ] = this[j];
        }
        //重新给当前数组插入合并后的数组值
        for(var k=0;k<newArr.length;k++){
            this[k] = newArr[k];
        }
        return this.length;
    }

	unshift  前加  返回数组长度
	push     后加  返回数组长度
	shift    前删  返回删除元素
	pop      后删  返回删除元素
	
/** 17、 Array.prototype.reduce() :  对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值 */
    // reducer 函数接收4个参数 ,一个功能强大的函数
    // arr.reduce(callback(累计器, 当前值, 当前索引, 原数组))
    // 详细参考MDN

/** 18、 Array.prototype.reverse() :  将数组中元素的位置颠倒,并返回该数组。该方法会改变原数组 */
    let arr = [1, 2, 3];
    arr.reverse(); console.log(arr); // [3, 2, 1]

    /** Polyfill */
    Array.prototype.reverse = function () {
        let res = []; 
        for (let i = 0; i < this.length; i++) {
            res[i] = this[this.length - i - 1]
        }
        return res;
    }

/** 19、 Array.prototype.slice() :  返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变 */
    let arr = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    let arr1 = arr.slice(1, 3); // ['bison', 'camel'] // 包括 begin,不包括end
    let arr2 = arr.slice(-2); //["duck", "elephant"] 倒数第二个元素到最后一个元素

    /** Polyfill */
    Array.prototype.slice = function(a, b){
        // 如果a是负数,另添加判断
        a=a||0;
        b=b||this.length;
        var ary=[];
        for(var i=a; i<b; i++){
            ary.push(this[i]);
        }
        return ary;
    }

/** 20、 Array.prototype.splice() :  通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组 */
    var myFish = ["angel", "clown", "mandarin", "sturgeon"];
    var removed = myFish.splice(2, 0, "drum"); 
    // removed = []; 插入 没有值
    // ["angel", "clown", "drum", "mandarin", "sturgeon"]  ----  插入元素  
    var removed = myFish.splice(3, 1); 
    // removed = ["sturgeon"]
    // 运算后的 myFish: ["angel", "clown", "mandarin"]      从第 3 位开始删除 1 个元素
    var removed = myFish.splice(2, 1, "trumpet");
    // 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"]
    // 被删除的元素: ["drum"]

    /** Polyfill */
    Array.prototype.splice = function(){
        var index,howmany;
        if(arguments.length == 0){
            this.length = 0;
            return this;
        }else if(arguments.length == 1){        //调整index和howmany的值
            index = arguments[0];
            if(index >= this.length){
                index = this.length;
            }else if(index < -this.length){
                index = 0;
            }else if(index < 0 && index >= -(this.length)){
                index += this.length;
            }
            howmany = this.length - index;
        }else if(arguments.length >= 2){        //调整index和howmany的值
            index = arguments[0];
            if(index >= this.length){
                index = this.length;
            }else if(index < -this.length){
                index = 0;
            }else if(index < 0 && index >= -(this.length)){
                index += this.length;
            }
            howmany = arguments[1];
            if(index+howmany >= this.length){
                howmany = this.length - index;
            }
    
        }
        var t1 = index;
        var length = arguments.length - 2;
        var arr = [];
        for(var i = 0 ; i < howmany ; i++){             // 返回删除的数组
            arr[i] = this[t1++];
        }
        var t2 = index;
        for(var i = t2 + howmany ; i < this.length ; i++){  //删除操作后的数组
            this[t2++] = this[i];
        }
        this.length = this.length - howmany;
    
        if(arguments.length > 2){                            //插入数
            var lastLength = this.length; 
            var leap = lastLength - index;
            var arIndexRigtht = arguments.length - 1;
            this.length = this.length + arguments.length - 2;
            for(var j = this.length - 1 ; j >= index ; j--){        
                if(leap > 0){
                    this[j] = this[j - arguments.length + 2];
                    leap = leap -1 ;
                }else{
                    this[j] = arguments[arIndexRigtht--];
                }
            }
        }
        return arr;
    }

/** 21、 Array.prototype.sort() :  用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的 */
    // arr.sort([compareFunction])  compareFunction(arg1, arg2): arg1\arg2 要比较的值
    // 1、按照值比较
    var numbers = [4, 2, 5, 1, 3]; 
    numbers.sort((a, b) => { return a - b; }); 
    console.log(numbers); // [1, 2, 3, 4, 5]
    // 按照属性 比较
    var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }];
    items.sort((a, b) => { return (a.value - b.value) });
    items.sort((a, b) => {
        var nameA = a.name.toUpperCase();
        var nameB = b.name.toUpperCase();
        if (nameA < nameB) return -1;
        if (nameA > nameB) return 1;
        return 0;// names must be equal
    });
    // 乱序
    arr.sort(function(a, b){ return Math.random() - 0.5; }); // 扩展
    /** Polyfill */

/** 22、 Array.prototype.toLocaleString() : 返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串 */
    parseInt('11123123231.3213').toLocaleString();  //  "11,123,123,231"      千位分隔符
    [1,'231',3,4].toLocaleString();   // "1, 231, 3, 4"

/** 23、 Array.prototype.toString() : 返回一个字符串,表示指定的数组及其元素。 */
    [1, 2, 'a', '1a'].toString();   // "1, 2, a, 1a"

/** 24、 Array.prototype.flat() : 返回一个字符串,表示指定的数组及其元素。 */
var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

/** Polyfill */
Array.prototype.flat = function(depth = 1) {
    if (!Number(depth) || Number(depth) < 0) {
        return this
    }
    let arr = this // 获得调用 fakeFlat 函数的数组
    while (depth > 0) {
        if (arr.some(item => Array.isArray(item))) {
             // 数组中还有数组元素的话并且 num > 0,继续展开一层数组 
            arr = [].concat.apply([], arr)
        } else {
            break // 数组中没有数组元素并且不管 num 是否依旧大于 0,停止循环。
        }
        depth--
    }
    return arr
}
const animals = ["🐷", ["🐶", "🐂"], ["🐎", ["🐑", ["🐲"]], "🐛"]];
animals.flat()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值