5

I have the "error: Cannot read property 'shorten' of undefined" error when running my test. I want my loop to run the shorten function to check if the string is longer then 20 characters, and if so limit it to that.

  function ListView(list) {
    this.list = list;
    this.converted;
  }

  ListView.prototype.convert = function() {
    var output = [];
    this.list.notelist.forEach(function(element) {
      this.shorten(element);
      output += "<li><div>" + element.text + "</div></li>";
    });
    this.converted = "<ul>" + output + "</ul>";
  };

  ListView.prototype.shorten = function(string) {
    if (string.length > 20) {
      return string.substring(0, 20);
    }
    return string;
  };

list is from another constructor but i mocked it with;

var mockList = { notelist: [{ text: "hello" }, { text: "goodbye" }] };
pyan
  • 865
  • 2
  • 12
  • 23
  • 2
    FYI, your `var output` should be initialized to an empty string, not an empty array. It works because of an empty array will be coerced to an empty string when the concatenation happens, but it's not really right. The `+=` doesn't add anything to the array. It just destroys it. –  Dec 30 '17 at 19:01
  • ...and this would be nicer with `.reduce()`, like this: `this.converted = this.list.notelist.reduce((s, el) => s + "
  • " + this.shorten(el) + "
  • ", "
      ") + "
    "` –  Dec 30 '17 at 19:04