"Cannot read property of undefined."
"Cannot read property of undefined."
我在 Python 中编写了一些简单的代码。它的工作。现在我正在尝试将其移植到 JavaScript。代码是here。我收到此错误:
sketch.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'compression_ratio')
at w (sketch.js:7:39)
at ifsp (sketch.js:37:13)
at draw (sketch.js:54:14)
at p5._main.default.redraw (p5.js:71990:27)
at _draw (p5.js:64140:25)
这里出了什么问题?
错误在这里(起始行 28)。
if (prob_sum > r) {
attractor_index = j - 1;
} else {
attractor_index = j;
}
如果 r
小于 1/3
(您在第 51 行中定义的概率值),您将使用 j - 1
递减 attractors_index
,如果这种情况发生在第一次迭代 attractors_index
将 -1
为 j = 0
。在那种情况下 attractors[attractors_index]
将 return undefined
并且您使用 undefined
调用 w()
而不是您期望的对象,因此 attractors.compression_ratio
不会有属性 compression_ratio
并抛出错误。
您可以通过手动将 r
设置为 >
或 <
1/3
.
轻松检查/重现
我在 Python 中编写了一些简单的代码。它的工作。现在我正在尝试将其移植到 JavaScript。代码是here。我收到此错误:
sketch.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'compression_ratio')
at w (sketch.js:7:39)
at ifsp (sketch.js:37:13)
at draw (sketch.js:54:14)
at p5._main.default.redraw (p5.js:71990:27)
at _draw (p5.js:64140:25)
这里出了什么问题?
错误在这里(起始行 28)。
if (prob_sum > r) {
attractor_index = j - 1;
} else {
attractor_index = j;
}
如果 r
小于 1/3
(您在第 51 行中定义的概率值),您将使用 j - 1
递减 attractors_index
,如果这种情况发生在第一次迭代 attractors_index
将 -1
为 j = 0
。在那种情况下 attractors[attractors_index]
将 return undefined
并且您使用 undefined
调用 w()
而不是您期望的对象,因此 attractors.compression_ratio
不会有属性 compression_ratio
并抛出错误。
您可以通过手动将 r
设置为 >
或 <
1/3
.