ES6中的Map()出错

时间:2018-06-09 12:43:35

标签: javascript reactjs dictionary redux depth-first-search

我正在尝试在React,Redux中实现DFS算法以使其可视化 要创建邻接列表,我在JavaScript中使用Map()数据结构:

dfs(v, visited, adjList) {
  console.log(v);
  visited[v] = true;

  var get_neighbours = adjList.get(v);

  for (var i in get_neighbours) {
    var get_elem = get_neighbours[i];
    if (!visited[get_elem])
      this.dfs(get_elem, visited, adjList);
  }
}

dfsStart(e) {
  var n = 0;
  var adjList = new Map();
  for (var i = 0; i < this.props.edges.length; i++) {
    n = Math.max(this.props.edges[i].u, this.props.edges[i].v);
  }
  for (var i = 1; i <= n; i++) {
    adjList.set(i, []);
  }
  for (var key of adjList.keys()) {
    console.log(key);
  }
  //console.log(adjList.size);
  for (var i = 0; i < this.props.edges.length; i++) {
    var x = this.props.edges[i].u;
    var y = this.props.edges[i].v;
    console.log(x + " " + y);
    [...adjList.get(x), y] - > where I am getting error
  }
  for (var key of adjList.values()) {
    console.log(key);
  }
  var visited = [];
  for (i = 1; i <= n; i++) {
    visited[i] = false;
  }
  this.dfs(1, visited, adjList);
}

我甚至尝试使用push()方法将值推送到空列表中,如下所示

adjList.get(x).push(y)

但这也给我一个错误!

  

未捕获的TypeError:无法将undefined或null转换为object       在Function.from()

当我使用push()时:

  

Layout.js:72 Uncaught TypeError:无法读取未定义的属性push       在Layout.dfsStart(Layout.js:72)

2 个答案:

答案 0 :(得分:0)

我想您想将最大x值取为n而不是最后一个x或y,更改:

for(var i=0;i<this.props.edges.length;i++)
  n = Math.max(this.props.edges[i].u, this.props.edges[i].v);

要:

n = Math.max(...this.props.edges.map(edge => edge.u));

答案 1 :(得分:0)

CustomPal <- function(new_pal){
  if (interactive()){
    colorfile <- paste(getwd(),"colorfile.txt",sep="/")
    if (!file.exists(colorfile)){
      file.create(colorfile)
    }
    shinyApp(
      ui = fluidPage(
        titlePanel("Cherry Pick Your Own Palette!"),
        sidebarPanel (hr(),
                      selectInput('col', 'Options', new_pal, multiple=TRUE, selectize=FALSE, size = 15)
        ),
        mainPanel(
          h5('Your custom colors',style = "font-weight: bold;"),
          fluidRow(column(12,verbatimTextOutput("col"))))
      ),
      server = function(input,output,session){
        outputdata<-  reactive({
          input$col
        })

        output$col <- { 
          renderPrint(outputdata())
        }
        session$onSessionEnded(function(){
          message <- paste(isolate(outputdata())," ")
          cat(message,file=colorfile, append=TRUE)
          customcolors <- scan(file=colorfile," ")
          stopApp(customcolors)
          customcolors
        })
      }
    )
  }
}

这样做可以解决问题,但是当我在console.log(get_neighbours)时,仍然在dfs()函数中给出了一个未定义的错误,