我在 http://www.somethinghitme.com/2013/11/11/simple-2d-terrain-with-midpoint-displacement/ 上发现了以下代码.
function terrain(width, height, displace, roughness, seed) {
var points = [],
// Gives us a power of 2 based on our width
power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2)))),
seed = seed || {
s: height / 2 + (Math.random() * displace * 2) - displace,
e: height / 2 + (Math.random() * displace * 2) - displace
};
// ...
}
我不熟悉这个语法。它究竟达到了什么目的?赋值后,points 变量将包含什么?
最佳答案
以下产生式是 Variable Statement ,它允许出现多个声明,用逗号分隔。
var points = [],
// Gives us a power of 2 based on our width
power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2)))),
seed = seed || {
s: height / 2 + (Math.random() * displace * 2) - displace,
e: height / 2 + (Math.random() * displace * 2) - displace
};
它的处理方式与使用单独的变量语句相同,并且选择使用哪种形式是一种风格偏好。 (我选择后者,jslint建议前者。)
var points = [];
var power = Math.pow(2, Math.ceil(Math.log(width) / (Math.log(2))));
var seed = seed || {
s: height / 2 + (Math.random() * displace * 2) - displace,
e: height / 2 + (Math.random() * displace * 2) - displace
};
值得注意的一件有趣的事情是 var Seed = Seed || ..
,其中 seed
已经是一个参数。这是因为 var
并不像 C 语言那样“定义”变量,而是声明应用了范围范围的注释。因此,整个作用域只有一个 seed
变量,再次使用 var
并没有什么区别 - 过去是,将来也永远是,一个局部变量。
参见What does "options = options || {}" mean in Javascript?用于使用种子|| ..
一般来说。
关于javascript - 赋值语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21635577/