hanyuxinting / Blog

记录点滴
1 stars 0 forks source link

JS权威指南读书笔记-5章 #2

Open hanyuxinting opened 7 years ago

hanyuxinting commented 7 years ago

Statements

以;分隔;make something change~

Expression Statements

var a = 'world'; var str = 'hello' + a; str
"helloworld"
var i = 2; i *= 3;
6
i++;
6
i
7
console.log(i)
VM248:1 7

Compound & Empty Statements

{
}

ES6 开始有了块级作用域~

Declaration Statements

var function

var

var i; // One simple variable
var j = 0; // One var, one value
var p, q; // Two variables
var greeting = "hello" + name; // A complex initializer
var x = 2.34, y = Math.cos(0.75), r, theta; // Many variables
var x = 2, y = x*x; // Second var uses the first
var x = 2, // Multiple variables...
      f = function(x) { return x*x }, // each on its own line
      y = f(x);

for(var i = 0; i < 10; i++) console.log(i);
for(var i = 0, j=10; i < 10; i++,j--) console.log(i*j);
for(var i in o) console.log(i);

在一个函数里,最好还是避免多次声明同一个变量,虽然这么做从语法上来说没问题,但从结果上来看,可能值会错乱。 但是如果到ES6里,使用let声明,就会好很多了~

function

var f = function(x) { return x+1; } // Expression assigned to a variable
function f(x) { return x+1; } // Statement includes variable name

示例:

function hypotenuse(x, y) {
    return Math.sqrt(x*x + y*y); // return is documented in the next section
}
function factorial(n) { // A recursive function
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}