为什么子类数组的JSON字符串化是一个对象

Why is the JSON stringification of a subclassed array an object?

本文关键字:一个对象 字符串 JSON 子类 数组 为什么      更新时间:2023-09-26

/* StackOverflow needs a console API */ console.log = function(x) { document.write(x + "<br />"); };
B = function() {}
B.prototype = Array.prototype;
var a = new Array();
var b = new B();
a[0] = 1;
b[0] = 1;
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));

JSON字符串将子类作为对象({ "0": 1 })而不是数组([1])`

有什么方法可以改变这种行为吗?

编辑

我正在使用(不可协商的)ES5。我稍微简化了这个例子。实际上,子类化是通过函数inherit()来设置的,该函数可以执行以下操作:

var inherit = function(base, derived) {
    function F() {}
    F.prototype = base.prototype;
    derived.prototype = new F();
    derived.prototype.constructor = derived;
};

据我所知,您不能从数组继承。一旦创建了构造函数,它的实例就会成为对象。当你想要一个数组的功能时,最好创建一个数组并在上面添加你想要的方法。这可以通过一个功能来完成:

function createExtendedArray () {
    var a = [];
    a.method1 = function() {};
    return a;
}
相关文章: