编程语言
首页 > 编程语言> > Java 005: Declaration and Assignment

Java 005: Declaration and Assignment

作者:互联网

let

let i, sum;
let message = "hello";
let i = 0, j = 0, k = 0;
let x = 2, y = x*x; // Initializers can use previously declared variables

If you don’t specify an initial value, the value is "undefined"

for(let i = 0, len = data.length; i < len; i++) console.log(data[i]);
for(let datum of data) console.log(datum);
for(let property in object) console.log(property);

const

const H0 = 74;         // Hubble constant (km/s/Mpc)
const C = 299792.458;  // Speed of light in a vacuum (km/s)
const AU = 1.496E8;    // Astronomical Unit: distance to the sun (km)
  • Constants cannot have their values changed, and any attempt to do so causes a TypeError to be thrown.
  • const works just like let except that you must initialize the constant when you declare it
for(const datum of data) console.log(datum);
for(const property in object) console.log(property);

In this case, the const declaration is just saying that the value is constant for the duration of one loop iteration

Variable Scope

  1. All variables and constants defined with let and const are block scoped
  2. Everything declared as part of the for loop are scoped by the loop body
  3. Variables declared at the top level are global scoped, i.e. the file that it is defined in

Repeated Declarations

  1. Ilegal to declare same variable twice in the same scope
  2. Legal to declare same variable twice in the nested scope
const x = 1;        // Declare x as a global constant
if (x === 1) {
    let x = 2;      // Inside a block x can refer to a different value
    console.log(x); // Prints 2
}
console.log(x);     // Prints 1: we're back in the global scope now
let x = 3;          // ERROR! Syntax error trying to re-declare x

Dynamically Typed

Javascript variables can hold a value of any type.

let i = 10;
i = "ten";

var

var x;
var data = [], count = data.length;
for(var i = 0; i < count; i++) console.log(data[i]);

" Unlike variables declared with let, it is legal to declare the same variable multiple times with var. And because var variables have function scope instead of block scope, it is actually common to do this kind of redeclaration. The variable i is frequently used for integer values, and especially as the index variable of for loops. In a function with multiple for loops, it is typical for each one to begin for(var i = 0; .... Because var does not scope these variables to the loop body, each of these loops is (harmlessly) re-declaring and re-initializing the same variable. "

Hoisting

When a variable is declared with var, the declaration is lifted up (or “hoisted”) to the top of the enclosing function.

标签:Java,Assignment,variables,console,variable,let,005,var,const
来源: https://blog.csdn.net/DOITJT/article/details/122215764