【发布时间】:2016-10-16 06:35:08
【问题描述】:
我一直在尝试找出一个解决方案,将单行句子(我在我的代码中称为“语句”)并在我的草图上将它们转换为多行句子。这个问题与another question I posted on SO 直接相关,我被要求将这个新问题作为一个新问题发布。
@KevinWorkman 的解决方案让我明白了这一点。但是,正在发生的事情是,当我尝试运行该程序时,我得到了一个TypeError: Cannot read property 'display' of undefined。草图加载,但是当我在草图中单击以开始动画时,我得到了那个错误。我认为这是因为我原来的statements[] 数组现在不再是可以在我的draw() 函数中调用的类型。但我的知识不足,无法知道问题出在哪里,而且我查看了所有 JS 和 p5.js 参考资料,但找不到解决方案。
我发布我的完整代码是为了提供一个最小的、完整的、可验证的示例。尽管如此,作为一名作家,我发现“最小”和“完整”是矛盾的术语,因此非常令人困惑,这里是:
var clContext;
var speed = 0.8;
var statements = [];
var canvas;
//load the table of Clinton's statements and their polarity
function preload() {
clContext = loadTable("cl_context_rev.csv", "header");
}
function setup() {
canvas = createCanvas(680, 420);
canvas.mousePressed(inWidth);
background(51);
noStroke();
// iterate over the table rows called in 'preload()' from .csv file
for (var i = 0; i < clContext.getRowCount(); i++) {
var statement = clContext.get(i, "statement");
var polarity = clContext.get(i, "polarity");
}
statements[i] = new Statement(polarity, statement);
}
function draw() {
if (mouseIsPressed) {
background(51);
for (var i = 0; i < statements.length; i++) {
statements[i].display();
}
}
}
// Function to align statements, categories, and polarity
function Statement(polarity, statement) {
// Break up single-line statements in order to display as multiline
this.statement = split(statement, "<br>");
this.polarity = polarity;
this.x = random(width);
this.y = random(height);
this.dx = random(-speed, speed);
this.dy = random(-speed, speed);
}
// Attach pseudo-class methods to prototype;
// Maps polarity to color and x,y to random placement on canvas
Statement.prototype.display = function() {
this.x += this.dx;
this.y += this.dy;
// Make statements reappear if they move off of the sketch display
if(this.x > width+10){
this.x = -10
}
if(this.y > height+10) {
this.y = -10
}
// Map positive/negative statements to colors
if(this.polarity == -1){
fill(229,121,59);
}
else if(this.polarity == 1){
fill(97,93,178);
}
textSize(14);
// Was directed to add both 'text' statements
text(this.statement[0], this.x, this.y);
text(this.statement[1], this.x, this.y+25);
}
// Create functions for hiding and showing statements
function inWidth() {
width = width+5;
};
注意:
console.log(typeof this.statement[0]) // returns 'undefined'
console.log(typeof this.statement[1]) // returns 'undefined'
console.log(split(statement, "<br>")) // returns 'undefined'
console.log(statements) // returns 'object'
console.log(statements.length) // returns 20
【问题讨论】:
标签: javascript string typeerror p5.js