var name = "John";
console.log(name); //輸出:John
var age = 23;
console.log(age); //輸出:23
var isMarried = false;
console.log(isMarried); //輸出:false
var hobbies = ["music", "reading", "swimming"];
console.log(hobbies); //輸出:[ "music", "reading", "swimming"]
var person = {name:"John", age:23, isMarried:false};
console.log(person); //輸出:{name:"John", age:23, isMarried:false}
二、運算符 在JavaScript中,運算符用于對變量進行數學和邏輯運算。以下是一些關于運算符的代碼及其運行結果示例:var x = 10;
var y = 5;
console.log(x + y); //輸出:15
console.log(x - y); //輸出:5
console.log(x * y); //輸出:50
console.log(x / y); //輸出:2
console.log(x % y); //輸出:0
console.log(x >y); //輸出:true
console.log(x< y); //輸出:false
三、控制語句 在JavaScript中,控制語句用于控制代碼塊的執行流程。以下是一些關于控制語句的代碼及其運行結果示例:var x = 10;
if(x % 2 === 0){
console.log("x is even"); //輸出:x is even
}else{
console.log("x is odd");
} //輸出:x is even
var i = 0;
while(i< 5){
console.log(i);
i++;
} //輸出:0,1,2,3,4
for(var i = 0; i< 5; i++){
console.log(i);
} //輸出:0,1,2,3,4
switch (new Date().getDay()) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
} //輸出:Tuesday(假設今天是星期二)
四、函數 在JavaScript中,函數被定義為一個獨立的可執行代碼塊。以下是一些關于函數的代碼及其運行結果示例:function calculateSquare(num){ return num * num; } console.log(calculateSquare(3)); //輸出:9
function calculateSum(num1, num2){ return num1 + num2; } console.log(calculateSum(5, 6)); //輸出:11
function printMessage(){ console.log("Hello World"); } printMessage(); //輸出:Hello World以上是一些關于JavaScript代碼運行結果的示例。在編寫代碼時,我們需要注意不同類型的代碼塊與運算符的順序和邏輯,并熟練地運用控制語句和函數。通過理解和掌握這些基本概念,我們可以更加輕松地編寫高效的JavaScript代碼。