8.20 pre day bug

发布于:2024-08-22 ⋅ 阅读:(21) ⋅ 点赞:(0)

pre-bug1

分号省略

这些语句的分隔规则会导致一些意想不到的情形,如以下的一个示例;

 let m = n + f
 (b+c).toString()

但该语句最终会被解析为:

 let m = n + f(a+b).toString();
 return
 true

一定会被解析成

 return;
 true;

pre-bug2

Math.random()与Math.floor()

Math.random()`方法是一个非常实用的内置函数,它被用来生成一个介于0(包含)和1(不包含)之间的随机浮点数,范围即 [0,1)

console.log(Math.random());

0.13560024799871395

0.004448119445554122

0.5884970635904845

Math.floor() 函数总是返回小于等于一个给定数字的最大整数

console.log(Math.floor(Math.random()));

0

console.log(Math.floor(Math.random()*10));

7

0

5

8

讓亂數乘上最大值 max 無條件捨去,得到的值區間會是 0~(max-1)

Math.floor(Math.random() * max)

加上 min ,得到值的區間為 min ~ (max-1+min)

Math.floor(Math.random() * max ) + min;

但我們要的區間值為 min ~ max ,所以 (max -1 + min) 必須寫成 (max -1 + min)+1-min ,所以最終寫法如下:

Math.floor(Math.random()*(max-min+1))+min;

pre-bug3

JS 中单引号和双引号无任何区别,二者均用于表示字符串字面量。 单引号和双引号混合使用时,内层引号将被视为字符串的一部分。 如果不使用单引号包含双引号或者双引号包含单引号,那么需要反斜杠对引号进行转义。 单引号和双引号之间的字符串可以相加。

pre-bug4

JavaScript 提升是指解释器在执行代码之前,似乎将函数、变量、类或导入的声明移动到其作用域的顶部的过程———MDN

let

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 1

let 声明的变量的作用域是最靠近并包含 let 声明的以下花括号闭合语法结构的一个:

var

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 2

var 声明的变量的作用域是最靠近并包含 var 语句的以下花括号闭合语法结构的一个:


网站公告

今日签到

点亮在社区的每一天
去签到