JavaScript initializing/appending/updating 数组数组
JavaScript initializing/appending/updating array of arrays
我是 javascript 的新手,已经研究了很长时间,但无法理解这种语法。当我尝试将一个数组推入另一个数组时,它会单独推入元素,而不是像我想要的那样创建一个数组数组。
我想做什么:
lastTimes
作为数组的数组:
lastTimes = [[1, 12435235], [2,443531923], [3,4925951]]
如果:IDandTime = [5, 5959393]
将 IDandTime
作为数组附加到 lastTimes
:
lastTimes = [[1, 12435235], [2,443531923], [3,4925951], [5, 5959393]]
或者如果 ID (IDandTime[0]
) 已经存在,则在 lastTimes
:
内更新该数组的时间
如果IDandTime = [1, 50305240]
将 ID 1 的时间更新为 50305240:
lastTimes = [[1, 50305240], [2,443531923], [3,4925951], [5, 5959393]]
有人介意帮我一下吗?我已经尝试了多种语法组合,但都无法正确解决问题,也没有成功找出合适的搜索词来找到预先存在的答案。非常感谢任何建议。
编辑:
代码:
var lastTimes = [];
var IDandTime = [1, 5935935];
lastTimes.push(IDandTime);
结果:
lastTimes = [1, 5935935]
我想要的结果:
lastTimes = [[1, 5935935]]
编辑2:
好的,这是我正在使用的完整功能。我有一个带有 XBee 串行模块的 node.js 服务器,以及几个带有 XBee 串行模块的 Arduino 温度传感器。我有一个握手机制在工作,但我正在尝试实现节点退出时的错误检查,因此不再使用它们的陈旧数据。我觉得这实际上只是基本二维数组语法的问题。
// Open a new serial port connection
sp.on("open", function (err) {
if (err) {
return console.log('Error opening port: ', err.message);
}
console.log('open');
var nodeCount = 0;
var nodes = []; // get rid of after debugging
var lastTimes = [];
lastTimes[0] = [0,0]; // initalize as 2D array for later
// Grab data from buffer
sp.on('data', function(data) {
// Initialize time Object
var time = new Date();
// Split incoming data by newline
var buffer0 = data.split('\n');
// New node handshake initiation received
if (buffer0 == "BROADCASTING") {
nodeCount++;
var sendID = nodeCount.toString();
sp.write(sendID);
console.log("Broadcast received. Sending identifier #" + sendID);
nodes.push(nodeCount);
}
// Preconnected node data received
if ((buffer0 != "BROADCASTING") && (nodeCount > 0)) {
var receiveTime = time.getTime();
// [ID, Temp] touple
var nodeData = buffer0[0].split(" ");
console.log("NodeID: " + nodeData[0] + " Temp(F): " + nodeData[1]);
// [ID, Time] touple
var IDandTime = [];
IDandTime.push(nodeData[0]);
IDandTime.push(time.getTime());
console.log("IDandTime: " + IDandTime);
// Check for preexisting node ID
var oldNode = 0;
var nodeIndex = 0;
for (var i = 0; i < lastTimes.length; i++) {
if (lastTimes[i][0] == IDandTime[0]) {
oldNode = 1;
nodeIndex = i;
}
}
// If new node, add new node data to lastTimes (list of [ID, Time] touples)
if (oldNode == 0) {
lastTimes[lastTimes.length] = IDandTime;
console.log("lastTimes: " + lastTimes);
}
// If preexisting node, update preexisting node time
else if (oldNode == 1) {
lastTimes[i][1] = IDandTime[1];
}
}
});
});
我上次尝试寻找正确语法的错误:
lastTimes[i][1] = IDandTime[1];
^
TypeError: Cannot set property '1' of undefined
您可以使用 findIndex
检查第一个数字是否在数组中的某些元素中,并更改原始数组中的该元素或将新元素推送到数组中。
var lastTimes = [[1, 12435235], [2,443531923], [3,4925951]];
function update(val) {
var i = lastTimes.findIndex(function(e) {
return e[0] == val[0];
});
if (i != -1) {
lastTimes[i][1] = val[1];
} else {
lastTimes.push(val);
}
}
update([1, 50305240])
console.log(lastTimes)
您可以使用纯对象(没有原型)而不是数组,如下所示:
var lastTimes = Object.create(null);
您可以设置此对象的属性,而不是推送元组。这样你就不必手动处理更新或附加,一切都会自动工作,就像这样:
var receiveTime = time.getTime();
// [ID, Temp] touple
var nodeData = buffer0[0].split(" ");
console.log("NodeID: " + nodeData[0] + " Temp(F): " + nodeData[1]);
// [ID, Time] touple
var IDandTime = [];
IDandTime.push(nodeData[0]);
IDandTime.push(time.getTime());
console.log("IDandTime: " + IDandTime);
lastTimes[nodeData[0]] = time.getTime();
迭代值:
Object.keys(lastTimes).forEach(id => {
var value = lastTimes[id];
});
通过 id 查找值只是:
var value = lastTimes[id];
首先,如果 data
是字符串,则调用 data.split('\n')
returns 数组(参见 String.prototype.split()
),因此您的每个比较 if (buffer0 == "BROADCASTING")
都是评估为 false
。你可能想比较数据的第一行,第一行在buffer0[0]
,所以写条件if (buffer0[0] == ... )
.
那你代码有误
// If preexisting node, update preexisting node time
else if (oldNode == 1) {
lastTimes[i][1] = IDandTime[1];
}
你在循环中使用变量 i
,但是因为循环没有用 break
关键字终止,循环总是遍历整个数组,循环结束后,变量i
设置为 lastTimes.length
,指向数组中不存在的索引。
我会这样写循环:
var IDandTime = [];
var nodeIndex = nodeData[0];
IDandTime.push(nodeIndex);
IDandTime.push(time.getTime());
var foundAtIndex;
for (var i = 0, l = lastTimes.length; i < l; i++) {
if (lastTimes[i][0] === nodeIndex) {
foundAtIndex = i;
break;
}
}
if (typeof foundAtIndex === 'undefined') {
lastTimes.push(IDandTime);
} else {
lastTimes[foundAtIndex] = IDandTime;
}
我是 javascript 的新手,已经研究了很长时间,但无法理解这种语法。当我尝试将一个数组推入另一个数组时,它会单独推入元素,而不是像我想要的那样创建一个数组数组。
我想做什么:
lastTimes
作为数组的数组:
lastTimes = [[1, 12435235], [2,443531923], [3,4925951]]
如果:IDandTime = [5, 5959393]
将 IDandTime
作为数组附加到 lastTimes
:
lastTimes = [[1, 12435235], [2,443531923], [3,4925951], [5, 5959393]]
或者如果 ID (IDandTime[0]
) 已经存在,则在 lastTimes
:
如果IDandTime = [1, 50305240]
将 ID 1 的时间更新为 50305240:
lastTimes = [[1, 50305240], [2,443531923], [3,4925951], [5, 5959393]]
有人介意帮我一下吗?我已经尝试了多种语法组合,但都无法正确解决问题,也没有成功找出合适的搜索词来找到预先存在的答案。非常感谢任何建议。
编辑:
代码:
var lastTimes = [];
var IDandTime = [1, 5935935];
lastTimes.push(IDandTime);
结果:
lastTimes = [1, 5935935]
我想要的结果:
lastTimes = [[1, 5935935]]
编辑2:
好的,这是我正在使用的完整功能。我有一个带有 XBee 串行模块的 node.js 服务器,以及几个带有 XBee 串行模块的 Arduino 温度传感器。我有一个握手机制在工作,但我正在尝试实现节点退出时的错误检查,因此不再使用它们的陈旧数据。我觉得这实际上只是基本二维数组语法的问题。
// Open a new serial port connection
sp.on("open", function (err) {
if (err) {
return console.log('Error opening port: ', err.message);
}
console.log('open');
var nodeCount = 0;
var nodes = []; // get rid of after debugging
var lastTimes = [];
lastTimes[0] = [0,0]; // initalize as 2D array for later
// Grab data from buffer
sp.on('data', function(data) {
// Initialize time Object
var time = new Date();
// Split incoming data by newline
var buffer0 = data.split('\n');
// New node handshake initiation received
if (buffer0 == "BROADCASTING") {
nodeCount++;
var sendID = nodeCount.toString();
sp.write(sendID);
console.log("Broadcast received. Sending identifier #" + sendID);
nodes.push(nodeCount);
}
// Preconnected node data received
if ((buffer0 != "BROADCASTING") && (nodeCount > 0)) {
var receiveTime = time.getTime();
// [ID, Temp] touple
var nodeData = buffer0[0].split(" ");
console.log("NodeID: " + nodeData[0] + " Temp(F): " + nodeData[1]);
// [ID, Time] touple
var IDandTime = [];
IDandTime.push(nodeData[0]);
IDandTime.push(time.getTime());
console.log("IDandTime: " + IDandTime);
// Check for preexisting node ID
var oldNode = 0;
var nodeIndex = 0;
for (var i = 0; i < lastTimes.length; i++) {
if (lastTimes[i][0] == IDandTime[0]) {
oldNode = 1;
nodeIndex = i;
}
}
// If new node, add new node data to lastTimes (list of [ID, Time] touples)
if (oldNode == 0) {
lastTimes[lastTimes.length] = IDandTime;
console.log("lastTimes: " + lastTimes);
}
// If preexisting node, update preexisting node time
else if (oldNode == 1) {
lastTimes[i][1] = IDandTime[1];
}
}
});
});
我上次尝试寻找正确语法的错误:
lastTimes[i][1] = IDandTime[1];
^
TypeError: Cannot set property '1' of undefined
您可以使用 findIndex
检查第一个数字是否在数组中的某些元素中,并更改原始数组中的该元素或将新元素推送到数组中。
var lastTimes = [[1, 12435235], [2,443531923], [3,4925951]];
function update(val) {
var i = lastTimes.findIndex(function(e) {
return e[0] == val[0];
});
if (i != -1) {
lastTimes[i][1] = val[1];
} else {
lastTimes.push(val);
}
}
update([1, 50305240])
console.log(lastTimes)
您可以使用纯对象(没有原型)而不是数组,如下所示:
var lastTimes = Object.create(null);
您可以设置此对象的属性,而不是推送元组。这样你就不必手动处理更新或附加,一切都会自动工作,就像这样:
var receiveTime = time.getTime();
// [ID, Temp] touple
var nodeData = buffer0[0].split(" ");
console.log("NodeID: " + nodeData[0] + " Temp(F): " + nodeData[1]);
// [ID, Time] touple
var IDandTime = [];
IDandTime.push(nodeData[0]);
IDandTime.push(time.getTime());
console.log("IDandTime: " + IDandTime);
lastTimes[nodeData[0]] = time.getTime();
迭代值:
Object.keys(lastTimes).forEach(id => {
var value = lastTimes[id];
});
通过 id 查找值只是:
var value = lastTimes[id];
首先,如果 data
是字符串,则调用 data.split('\n')
returns 数组(参见 String.prototype.split()
),因此您的每个比较 if (buffer0 == "BROADCASTING")
都是评估为 false
。你可能想比较数据的第一行,第一行在buffer0[0]
,所以写条件if (buffer0[0] == ... )
.
那你代码有误
// If preexisting node, update preexisting node time
else if (oldNode == 1) {
lastTimes[i][1] = IDandTime[1];
}
你在循环中使用变量 i
,但是因为循环没有用 break
关键字终止,循环总是遍历整个数组,循环结束后,变量i
设置为 lastTimes.length
,指向数组中不存在的索引。
我会这样写循环:
var IDandTime = [];
var nodeIndex = nodeData[0];
IDandTime.push(nodeIndex);
IDandTime.push(time.getTime());
var foundAtIndex;
for (var i = 0, l = lastTimes.length; i < l; i++) {
if (lastTimes[i][0] === nodeIndex) {
foundAtIndex = i;
break;
}
}
if (typeof foundAtIndex === 'undefined') {
lastTimes.push(IDandTime);
} else {
lastTimes[foundAtIndex] = IDandTime;
}