gpt4 book ai didi

javascript - 如何在javascript中将元素添加到字典中的列表中?

转载 作者:行者123 更新时间:2023-12-03 03:49:45 24 4
gpt4 key购买 nike

我在 javascript 中使用一种字典,并且想要将一个元素添加到作为字典一部分的列表中。

这是代码片段:

lines = [
[1,2],
[2,4],
[2,3],
[3,5]
];

nodes = [1,2,3,5,4];

function get_adjdict(nodes, lines) {
// create an empty something
adjacent = [];
// loop over all elements on the array 'nodes'. The variable 'node' is supposed to take the various values of the elements in 'nodes'. So in this example this will be the values 1,2,3,5,4.
for (var node in nodes) {
// Add a key-value pair to the object/array/whatever named 'adjacent'. key is the value of 'node, the value is an empty array.
adjacent.push({node:[]});
// loop over all elements on the array 'lines'. The variable 'line' is supposed to take the various values of the elements in 'lines'. So in this example this will be the values [1,2], then [2,4] and so on
for (var line in lines) {
// checks if the value of 'node' is present in the array 'line'
if (line.includes(node)) {
// If the first element of the array 'line' has the same value as 'node'...
if (line[0] == node) {
// ... add the second element of 'line' to 'adjacent[node]'
adjacent[node].push(line[1]) //ERROR
} else {
// ... add the first element of 'line' to 'adjacent[node]'
adjacent[node].push(line[0])
}

}
}
}
return adjacent
}

错误是“TypeError:相邻[节点].push不是函数”。那该怎么办呢?

预期的数据结构:

adjdict = {
1: [2],
2: [1,4,3],
3: [2,5],
4: [2],
5: [3]
}

最佳答案

这就是您正在寻找的:

var lines = [
[1,2],
[2,4],
[2,3],
[3,5]
];

var nodes = [1,2,3,4,5];

function get_adjdict (nodes, lines) {
var adjacent = {};
var node, line;

for (var node_idx in nodes) {
node = nodes[node_idx];
adjacent[node] = [];

for (var line_idx in lines) {
line = lines[line_idx];

if (line.includes(node)) {
if (line[0] == node) {
adjacent[node].push(line[1]);
} else {
adjacent[node].push(line[0]);
}

}
}
}
return adjacent;
}

get_adjdict(nodes, lines);

请记住,在 JavaScript 中使用构造 for (var idx in arr) {} 时,idx 是迭代中的键,而不是值。

for (var node in nodes) {

在上面的代码中,node 取值04nodes[node] 将采用值 15,正如我认为您所期望的那样。

我总是对这种变量使用后缀_idx。在本例中,将 node 重命名为 node_idxnode_index,您将看到一切如何就位。

关于javascript - 如何在javascript中将元素添加到字典中的列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45217358/

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