gpt4 book ai didi

javascript - 如何连接两个子类数组?

转载 作者:行者123 更新时间:2023-11-30 17:51:46 24 4
gpt4 key购买 nike

我有两个数组子类:节点和信标。当我在它们的两个实例上运行 .concat 时,它会创建一个包含 2 个元素的新数组:整个节点数组实例和整个信标数组实例。我应该怎么做才能使其按预期工作?

节点.js

mgm.Nodes = function() {
Array.apply(this, arguments);
this.fetch();
};

mgm.Nodes.prototype = Object.create(Array.prototype);
mgm.Nodes.prototype.constructor = mgm.Nodes;

mgm.Nodes.prototype.create = function(data) {
//mgm.Node is an object and should be fine to replace with Object for testing purposes
var node = new mgm.Node(data);
this.push(node);
return node;
};

mgm.Nodes.prototype.get = function(id) {
};

mgm.Nodes.prototype.fetch = function() {
var n = 20;
for (var i = 0; i < n; i++) {
var data = {
id: i,
attributes: {name: undefined,}
};
this.create(data);
}
};

mgm.Nodes.prototype.remove = function(node) {
return this.splice(this.indexOf(node), 1)[0];
};

mgm.Nodes.prototype.update = function(node) {
// TODO: bind this to node.on('save')
};

信标.js

mgm.Beacons = function() {
this.fetch();
};

mgm.Beacons.prototype = Object.create(Array.prototype);
mgm.Beacons.constructor = mgm.Beacons;

mgm.Beacons.prototype.create = function(data) {
//mgm.Beacon is an object and should be fine to replace with Object for testing purposes
var beacon = new mgm.Beacon(data);
this.push(beacon);
return beacon;
};

mgm.Beacons.prototype.fetch = function() {
this.create({x: 200, y: 150, fixed: true, tag: ''});
};

运行它会得到一个长度为 2 的数组(预期为 21),其中第 0 个元素的长度为 20:

var nodes = new Nodes();
var beacons = new Beacons();
console.log(nodes.concat(beacons));

最佳答案

It creates a new array with 2 elements: the entire nodes array instance, and the entire beacons array instance.

那是因为它们不是数组实例。看什么the concat method判断待串接对象是否逐项串接:

If the value of the [[Class]] internal property of E is "Array", then

[iterate E and push each single element]

else [将E作为一个整体放在结果数组上]

你的 BeaconsNodes 可能继承自 Array.prototype,但它们是简单的对象 - 没有特殊的 [[Class]],没有自动调整 length 属性。顺便说一句,Array.apply(this, arguments); 没有按预期工作,它只是创建了一个新数组。使用 this.push.apply(this, arguments);

What should I do to make it work as expected?

你可以用你自己的实现覆盖concat:

mgm.Nodes.prototype.concat = mgm.Beacons.prototype.concat = function concat(other) {
var O = Object(this),
A = new Array(), // new this.constructor() ?
n = 0,
items = [O];
items.push.apply(items, arguments);
while (items.length > 0) {
var E = items.shift();
if (typeof E.length == "number") { // not: Array.isArray(E)
var k = 0,
len = E.length;
while (k < len) {
var P = ""+k;
if (Object.prototype.hasOwnProperty.call(E, P)) {
var subElement = E[P];
A[n] = subElement;
n++;
}
k++;
}
} else { // E is not Array-like
A[n] = E;
n++;
}
}
return A;
};

关于javascript - 如何连接两个子类数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18860159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com