我想将此值推送到router.PORTS [i] .packetdata 但它没有给我确切的价值..推送功能也循环 并给我错误的价值.. 错误的代码在第72行。
但是当我尝试的时候 router.PORTS [i] .packetdata = message; 在第72行。 值是正确的,但它没有推向数组。
function Router(PORTS){
rex = this;
}
Router.prototype = {
"PORTS": [],
connect: function(devicename,PORT){
devicename.PORT = PORT;
this.PORTS.push(devicename);
},
totalPackets: function(PORT){
if(PORT){
for (var i=0;i<rex.PORTS.length;i++)
{
if(rex.PORTS[i].PORT == PORT){
console.log('total packets by PORT', rex.PORTS[i])
}
}
}else{
return rex.packetdata.length;
}
},
totalBytes: function(){
totalBytes = [];
result = 0;
for (var i=0;i<rex.packetdata.length;i++)
{
totalBytes.push(rex.packetdata[i].message.length)
}
for (var i = 0; i< totalBytes.length; i++) {
result += totalBytes[i];
}
return result;
},
packetdata: []
}
function Device(ip){
this.ip = ip;
}
Device.prototype = {
DeviceName: "",
IP: this.ip,
PORT: "",
data:[],
incomingBuffer: "",
totalPackets:"",
totalBytes:"",
emit: function(data,packets){
rex.packetdata.push(packets);
},
packetdata: []
}
function Packet(ip,message) {
this.ip = ip;
this.message = message;
for (var i=0;i<rex.PORTS.length;i++)
{
if(router.PORTS[i]['ip'] == ip){
router.PORTS[i].incomingBuffer = router.PORTS[i].incomingBuffer + this.message;
// I want to push this value to router.PORTS[i].packetdata
// my code router.PORTS[i].packetdata.push(message);
router.PORTS[i].packetdata = message;
console.log(ip, router.PORTS[i].ip);
}
else{
//console.log('invalid')
}
}
}
Packet.prototype = {
ip: this.ip,
message: this.message
};
router = new Router(['WAN', 'LAN1', 'LAN2']);
device1 = new Device('192.168.0.1');
router.connect(device1, 'LAN1');
device2 = new Device('192.168.0.10');
router.connect(device2, 'LAN2');
wan = new Device('62.88.120.10');
router.connect(wan, 'WAN');
wan.emit('data', new Packet('192.168.0.1', 'Hello '));
wan.emit('data', new Packet('192.168.0.10', 'Hi,'));
wan.emit('data', new Packet('192.168.0.10', ' guys'));
wan.emit('data', new Packet('192.168.0.1', 'world!'));
wan.emit('data', new Packet('192.168.0.1', 'shit!'));
router.totalPackets();
router.totalBytes();
router.totalPackets('LAN1');
答案 0 :(得分:0)
这看起来像是一个错误:
Device.prototype = {
// ...
packetdata: []
}
创建一个单独的数组,每次实例化新的packetdata
时,该数组将被指定为Device
属性。因此,当您修改一个Device
的{{1}}时(除非已重新分配其packetdata
属性),您正在修改一个数组,这会影响每个packetdata
。
您可以通过在构造函数中创建每个Device
来创建一个新的packetdata
数组。
Device
或者,您可以坚持使用原始原型,但将数组视为不可变值。所以要将数据包数据添加到设备,而不是改变数组
function Device(ip) {
this.ip = ip;
this.packetdata = [];
}
你可以重新分配它
device.packetdata.push(message);
但这是一个相当不典型的设计,因为大多数javascript程序员不会考虑不可变数据结构。