JS中的類數組加上splice屬性的區別以及一些注意點

類數組中:

如果沒有 splice 打印出來的是一個對象形式的結果

    var obj = {
        "2": 3,
        "3": 4,
        length: 2,
    };
    console.log(obj);
//{2: 3, 3: 4, length: 2}

在這裏插入圖片描述

如果加了 splice,打印出來,就是一個數組形式的結果

    var obj = {
        "2": 3,
        "3": 4,
        length: 2,
        splice: Array.prototype.splice
    };
    console.log(obj);
    //Object(2) [empty × 2, 2: 3, 3: 4, splice: ƒ]

關於類數組的一些注意點:

    var obj = {
        "2": 3,
        "3": 4,
        length: 2,
        push: Array.prototype.push
    };
    obj.push(1);
    obj.push(2);
    console.log(obj);
//{2: 1, 3: 2, length: 4, push: ƒ}

注意這裏的返回結果,obj 並沒有4個屬性,相當於修改的原來的屬性,但長度變成了4。
原理就是 push 方法的源碼:

Array.prototype.push = function () {
        for (var arg in arguments) {
            if (arguments.hasOwnProperty(arg)) {
                this[this.length] = arguments[arg];//push的時候,這裏使用的是 length 屬性
            }
        }
        return this.length;
    };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章