我在运行测试时遇到“错误:无法读取未定义的‘缩短’属性”错误。我希望我的循环运行缩短函数来检查字符串是否超过 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" }] };
最佳答案
您的代码存在一些问题:
您遇到了这是什么问题,这是初学者很常见的问题,请查看 this link 。在
function (element) { ..
的匿名函数体中,它不会获取您的自定义类型的上下文,因此this
是对您的浏览器窗口的引用。您的
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/