javascript - 无法读取循环内函数未定义的属性

标签 javascript string foreach dom-manipulation

我在运行测试时遇到“错误:无法读取未定义的‘缩短’属性”错误。我希望我的循环运行缩短函数来检查字符串是否超过 20 个字符,如果超过 20 个字符,则将其限制为 20 个字符。

  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 来自另一个构造函数,但我用它来模拟它;

var mockList = { notelist: [{ text: "hello" }, { text: "goodbye" }] };

最佳答案

您的代码存在一些问题:

enter image description here

  1. 您遇到了这是什么问题,这是初学者很常见的问题,请查看 this link 。在 function (element) { .. 的匿名函数体中,它不会获取您的自定义类型的上下文,因此 this 是对您的浏览器窗口的引用。

  2. 您的 shorten 方法在其语义中以不同的用法被调用。您没有获取它返回的内容,但是 element 根本没有被该方法修改。

那么,让我们尝试更正您尝试执行的代码:

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

    ListView.prototype.convert = function () {
        var output = [];

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

    ListView.prototype.shorten = function (el) {
        var string = el.text;

        if (string.length > 20) {
            el.text = string.substring(0, 20);
        }
    };

    var mockList = { notelist: [{ text: "hello" }, { text: "goodbye0123456789012345" }] };
    var listview1 = new ListView(mockList);
    listview1.convert();
    alert(listview1.converted);

</script>

goodbye0123456789012345 是为了测试特意修改的,结果会缩短为 goodbye0123456789012

关于javascript - 无法读取循环内函数未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48036799/

相关文章:

javascript - 在 JavaScript 中使用 If 语句

java - 此代码是否线程安全,使用 Java 8 Lambdas - stream.forEach

c# - 我可以在 C# winforms 中使用 foreach 循环评估两组项目吗?

php - 单击按钮时从表中获取值

javascript - 如何在 JavaScript 中旋转 iFrame 中的 URL

javascript - 如何使用 JS Regex 从 google 查询链接获取查询值? (Chrome 扩展)

string - 查找两个变量名标量的并集

json - 使用 foreach Play Framework .json 模板列表对象?

javascript - Google Pub/Sub 如何在 Pull 上设置读取超时

c - 如何写出标记化的字符串