javascript - 赋值语法

标签 javascript syntax

我在 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/

相关文章:

javascript - 多边无向图的循环枚举

javascript - 注册 ServiceWorker 返回 AbortError 代码 :20

java - golang为[z][y][x]int定义数组int[x][y][z]有什么好处?

string - 多行字符串文字的语法是什么?

javascript - IIFE 前的分号有什么用?

javascript - 是否可以在 Billboard.js 的图表上显示消息文本?

javascript - 工具提示不适用于提交按钮

javascript - 编辑接触 Angular 时用值填充输入框

c - C样式语法的客观优势

Mysql连续3个单引号