首页 > 为什么 js用 length 和 splice 能创建类数组对象?

为什么 js用 length 和 splice 能创建类数组对象?

var obj = {
    length: 0,
    splice: function() {}
};
//console.log(obj) => []而不是{}
//jQuery里面就用这个模拟数组行为的
//类似这样:
var arr = [],
    splice = arr.splice,
    push = arr.push,
    obj = {
        length: 0,
        splice: splice,
        push: push
    };
//obj.push(1) => [1]

这个是什么原理?


第一个还是对象不是Array console.log(obj instanceof Array) ==false


题主应该是在Chrome里测试的吧。
在FireFox测试的是这样的。

所以,这个不是什么原理。只是浏览器不同的表现而已。

进一步讲,通过下面的函数,也能判断出是否为ArrayLike。

function isArraylike( obj ) {
    var length = obj.length,
        type = jQuery.type( obj );

    if ( type === "function" || jQuery.isWindow( obj ) ) {
        return false;
    }

    if ( obj.nodeType === 1 && length ) {
        return true;
    }

    return type === "array" || length === 0 ||
        typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}

http://stackoverflow.com/questions/11886578/creating-array-like-objects-in-javascript

【热门文章】
【热门文章】