我是 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)
关于JavaScript 初始化/追加/更新数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39690594/