如何在javascript中向dict中的列表添加元素?

时间:2017-07-20 14:17:42

标签: javascript dictionary

我在javascript中使用了一种dict,并希望将一个元素添加到列表中,该列表是一种字典的一部分。

以下是代码段:

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:相邻[node] .push不是函数”。怎么办呢?

预期的数据结构:

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

4 个答案:

答案 0 :(得分:1)

这就是你要找的东西:

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将值0带到4。正如我认为您所期待的那样,nodes[node]会将值1带到5

我总是使用后缀_idx来表示这种变量。在这种情况下,将node重命名为node_idxnode_index,您就会看到所有内容都会落实到位。

答案 1 :(得分:0)

不要在数组上使用for/in循环。他们可以最终迭代继承的属性以及数组项。 for/in用于对象迭代。使用.forEach()代替将更简单地处理枚举项目(无需管理索引)。

接下来,您指示要输出的对象,但是您要将adjacent创建为数组。数组继承自对象,但它们以不同方式存储数据。

另外,请记住正式声明您的变量,否则它们会变成全局变量。

最后,不要依赖自动分叉插入。这可能会导致某些边缘情况出现错误。

如果你遵循良好的编码最佳实践,很多这类问题就会消失。



// Don't forget to use "var" to declare your variables otherwise
// they will become global.
var nodes = [1,2,3,4,5];

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

function get_adjdict(nodes, lines) {
  var adjacent = {};  // <-- You are asking for an object, not an array
    
  // Loop through the nodes array (use .forEach() to loop arrays)
  nodes.forEach(function(node){
    
    // Array to store results in
    var results = [];
    
    // Loop through the lines
    lines.forEach(function(line) {
      if (line.includes(node))  {
          if (line[0] === node) {
            results.push(line[1]);
          } else {
            results.push(line[0]);
          }
          // Set array as new property value
          adjacent[node] = results;
      }
     });      
  });
  // This needs to be outside of all loops, just before function terminates
  return adjacent; 
}

console.log(get_adjdict(nodes, lines));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

首先映射所有索引,然后使用简单的reduce来构建对象,可以简化它。

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

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

// Make a lookup table where all the numbers appear
var lookup = lines.slice(0).reduce( (o, node, i) => {        
    o[node[0]] = o[node[0]] || []; // if we have not found it, set an array
    o[node[0]].push(node[1]); // add index value to the array
    o[node[1]] = o[node[1]] || []; // if we have not found it, set an array
    o[node[1]].push(node[0]); // add index value to the array
  return o  //return object for reduce
}, {})

var result = nodes.reduce( (o, n) => { //now loop over the nodes and make the `hash` table
  o[n] = lookup[n] || []
  return o
}, {})

console.log(result)

答案 3 :(得分:0)

你可以迭代这些线并创建对象。

function add(o, k, v) {
    if (!o[k]) {
        o[k] = [];
    }
    if (o[k].indexOf(v) === -1) {
        o[k].push(v);
    }
}

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

lines.forEach(function (l) {
    add(result, l[0], l[1]);
    add(result, l[1], l[0]);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }