函数返回值

函数返回值

在自定义的函数中使用返回值

要从自定义函数返回值,你需要使用 return 关键字。我们最近在 random-canvas-circles.html 示例中见过此用法。我们的 draw() 会在 HTML 元素上随机绘制 100 个圆圈:

jsfunction draw() {

ctx.clearRect(0, 0, WIDTH, HEIGHT);

for (let i = 0; i < 100; i++) {

ctx.beginPath();

ctx.fillStyle = "rgb(255 0 0 / 50%)";

ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);

ctx.fill();

}

}

在每次循环中,random() 函数被调用了三次,分别生成圆圈的 x 坐标、y 坐标和半径的随机值。random() 函数接收一个整数参数,并返回一个介于 0 到该参数的随机整数:

jsfunction randomNumber(number) {

return Math.floor(Math.random() * number);

}

这个函数也可以写成这样:

jsfunction randomNumber(number) {

const result = Math.floor(Math.random() * number);

return result;

}

但是第一个版本写起来更快,而且更简洁。

我们每次调用函数都返回 Math.floor(Math.random() * number) 的计算结果。该返回值会直接出现在函数被调用的位置,代码随后继续执行后续逻辑。

例如,当执行以下代码时:

jsctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);

假设三次 random() 调用分别返回 500、200 和 35,则这行代码实际等价于:

jsctx.arc(500, 200, 35, 0, 2 * Math.PI);

首先运行该行的函数调用,并将其返回值替换为函数调用,然后再执行该行本身。

🌟 相关推荐

荚的解释
365bet体育投注网站

荚的解释

📅 11-11 👀 9471
html5如何设置网页宽度
365bet体育投注网站

html5如何设置网页宽度

📅 08-07 👀 6069
Haiti地图,位置、地点、地址、在哪里
365bet开户地址

Haiti地图,位置、地点、地址、在哪里

📅 09-08 👀 5761