[英]Global object is undefined even after updating it in a function
作為 C++ 的用戶,並且對 web-dev 完全陌生,我無法理解為什么全局變量“angle”沒有在函數 setup() 內更新。 因為,在我運行 console.log(angle[1].arc_colour) 的最后一行,它返回我未定義。 但是,如果我嘗試在控制台中打印相同的命令,則會返回一個有限數字。
(注意:setup() 是 p5.js 中的一個函數,它在每次執行時首先被調用)
//quick.js var angle = new Array(200); function Drawn_Arc(begin_angle, end_angle, arc_colour) { this.begin_angle = begin_angle; this.end_angle = end_angle; this.arc_colour = arc_colour; } function swap(a, b) { a = a + b; b = a - b; a = a - b; } function setup() { createCanvas(windowWidth, windowHeight); background(230); noStroke(); colorMode(HSL, 2000); for (let i = 1; i <= 200; i++) { angle[i - 1] = new Drawn_Arc(((i - 1) * PI) / 100, (i * PI) / 100, random(0, 2000)); fill(angle[i - 1].arc_colour, 2000, 1000); arc(windowWidth / 2, windowHeight / 2, windowHeight - 12, windowHeight - 12, angle[i - 1].begin_angle, angle[i - 1].end_angle, PIE); } } console.log(angle[1].arc_colour);
//---html--- <html style="margin : 0px; padding : 0px"> <head> <meta charset="utf-8" /> <title>Quick Sort</title> </head> <body style="margin : 0px; padding : 0px"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script> <script type="text/javascript" src="quick.js"></script> </body> </html>
[...] 全局變量 'angle' 未在函數
setup()
內更新。 因為,在我運行console.log(angle[1].arc_colour)
的最后一行,它返回我未定義。
線onsole.log(angle[1].arc_colour);
不在setup
函數中,但它在全局范圍內的腳本末尾。
移動console.log(angle[1].arc_colour);
進入設置函數,以便在數組初始化后完成:
function setup() {
createCanvas(windowWidth, windowHeight);
background(230);
noStroke();
colorMode(HSL, 2000);
for (let i = 1; i <= 200; i++) {
angle[i - 1] = new Drawn_Arc(((i - 1) * PI) / 100, (i * PI) / 100, random(0, 2000));
fill(angle[i - 1].arc_colour, 2000, 1000);
arc(windowWidth / 2, windowHeight / 2, windowHeight - 12,
windowHeight - 12, angle[i - 1].begin_angle, angle[i - 1].end_angle, PIE);
}
console.log(angle[1].arc_colour);
}
// console.log(angle[1].arc_colour);
如果我想在其他函數中使用數組怎么辦。 我該怎么做?
當然,您也可以在函數中記錄數組:
function setup() {
createCanvas(windowWidth, windowHeight);
// ......
logarray();
}
function logarray()
{
console.log(angle[1].arc_colour);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.