JavaScript 變數

"use strict";

'use strict';

嚴格模式使 JavaScript 更加嚴格,以確保你的最佳習慣。例如,分配變數:

"use strict"; // or 'use strict';
var syntax101 = "var is used when assigning a variable.";
uhOh = "This is an error!";

uhOh 應該使用 var 來定義。嚴格模式,開啟,顯示錯誤(在控制檯中,它不關心)。用它來產生定義變數的好習慣。

你可以使用巢狀陣列和物件。它們有時很有用,而且它們也很有趣。以下是它們的工作原理:

巢狀陣列

var myArray = [ "The following is an array", ["I'm an array"] ];

console.log(myArray[1]); // (1) ["I'm an array"]
console.log(myArray[1][0]); // "I'm an array"

var myGraph = [ [0, 0], [5, 10], [3, 12] ]; // useful nested array

console.log(myGraph[0]); // [0, 0]
console.log(myGraph[1][1]); // 10

巢狀物件

var myObject = {
    firstObject: {
        myVariable: "This is the first object"
    }
    secondObject: {
        myVariable: "This is the second object"
    }
}

console.log(myObject.firstObject.myVariable); // This is the first object.
console.log(myObject.secondObject); // myVariable: "This is the second object"

var people = {
    john: {
        name: {
            first: "John",
            last: "Doe",
            full: "John Doe"
        },
        knownFor: "placeholder names"
    },
    bill: {
        name: {
            first: "Bill",
            last: "Gates",
            full: "Bill Gates"
        },
        knownFor: "wealth"
    }
}

console.log(people.john.name.first); // John
console.log(people.john.name.full); // John Doe
console.log(people.bill.knownFor); // wealth
console.log(people.bill.name.last); // Gates
console.log(people.bill.name.full); // Bill Gates