困惑理解闭包

时间:2018-01-22 03:12:16

标签: javascript closures

从概念上讲,闭包对于发生的事情有一点意义,但在实践中,我不知道发生了什么。对于我正在处理的问题,我想计算我读入的数字的出现次数并将其存储在直方图中。这应该发生在countOccurences函数中,但直方图数组永远不会更新。

var LinkedList = function() {
this.head = null;
}

LinkedList.prototype.add = function(val) {
  this.head = {data: val, next: this.head};
};

LinkedList.prototype.forEach = function(action) {
   for (var temp = this.head; temp; temp = temp.next) {
     action(temp.data);
   }   
 };
 // This is where the closure concept should take effect
 var countOccurrences = function(histogram) { 

     return function(val){ // Not working as expected, The val should equal 
                        // a number found in the list. Take for example if 
                        // 1 is found then histogram[1]++. Meaning we've  
                        // seen the number 1 once in the list so far. This
                        // continues until the entire list has been processed.
       histogram[val]++;
     }; 
  }

 function printHistogram(histogram) {
     for (var i in histogram) {
         if (histogram[i]) {
           println("(#" + i + ":" + histogram[i] +")")
         }   
     }
  }

var main = function() {
    var list = new LinkedList(); //Creates empty linkedlist
    var histogram = [];
    while (ln = readln().trim()) { //Reads in numbers from stdin
         list.add(ln)
    }   
    list.forEach(countOccurrences(histogram))
    printHistogram(histogram)
}; main()

2 个答案:

答案 0 :(得分:0)

你的闭包实际上并没有返回一个函数。不完全确定你是如何计算或这些值将是什么,但你肯定需要从你的闭包返回你的函数开始。



var LinkedList = function() {
  this.head = null;
}

LinkedList.prototype.add = function(val) {
  this.head = {
    data: val,
    next: this.head
  };
};

LinkedList.prototype.forEach = function(action) {
  for (var temp = this.head; temp; temp = temp.next) {
    action(temp.data);
  }
};
// This is where the closure concept should take effect
var countOccurrences = function(histogram) {

  return function(val) { // Not working as expected, I'm tring to get val to
    // be the data passed in from forEach which will 
    // then be incremeted accordingly in the histogram 
    // array
    histogram[val] = histogram[val] ? histogram[val] + 1 : 1;
  };
}

function printHistogram(histogram) {
  for (var i in histogram) {
    if (histogram[i]) {
      println("(#" + i + ":" + histogram[i] + ")")
    }
  }
}

var main = function() {
  var list = new LinkedList(); //Creates empty linkedlist
  var histogram = [];
  while (ln = readln().trim()) { //Reads in numbers from stdin
    list.add(ln)
  }
  list.forEach(countOccurrences(histogram))
  printHistogram(histogram)
};
main()




答案 1 :(得分:0)

由于最初缺乏退货声明,实际的关闭是错误的。然而,在那之后,我发现了另一个与关闭无关的错误。问题在于函数,因为我正在递增一个未初始化的数字。所以修复如下:

var countOccurrences = function(histogram) {

    return function(val) { 
       if(histogram[val])
          histogram[val]++;
       else
          histogram[val] = 1;
    };
   }

无论如何,帮助都有很多帮助。