JavaScriptBasics语法

LearningJavaScript coreBasics, includingvariable, dataclass型, 运算符 and 控制语句

1. JavaScriptIntroduction

JavaScript is a轻量级 解释型programminglanguage, 主要用于网页交互 and 动态效果. 它 is WebDevelopment 三 big coretechniques之一 (HTML, CSS, JavaScript) .

1.1 JavaScript 特点

  • 解释型language: 不需要编译, 直接由浏览器解释执行
  • 弱class型language: variableclass型可以动态改变
  • 面向object: support原型inheritance 面向objectprogramming
  • event驱动: throughevent响application户交互
  • 跨平台: 可以 in 不同浏览器 and operationsystem on run

1.2 JavaScript application场景

  • 网页动态效果 and 交互
  • 表单verification
  • AJAXasynchronous通信
  • before 端framework and library (such asReact, Vue, Angular)
  • server端Development (Node.js)
  • moveapplicationDevelopment (React Native, Ionic)
  • 桌面applicationDevelopment (Electron)

2. JavaScriptbasic语法

JavaScript 语法class似于C and Java, 但 has 一些独特之处.

2.1 variable声明

JavaScript has 三种variable声明方式: var, let and const.

// usingvar声明variable (function作用域) 
var name = "张三";

// usinglet声明variable (块级作用域) 
let age = 25;

// usingconst声明常量 (块级作用域, 不可重 new 赋值) 
const PI = 3.14159;

2.2 dataclass型

JavaScript has 7种basicdataclass型 and 1种引用dataclass型.

basicdataclass型

  • Number: numberclass型, including整数 and 浮点数
  • String: stringclass型
  • Boolean: booleanclass型, 值 for true or false
  • Null: 表示null
  • Undefined: 表示undefined 值
  • Symbol: 表示唯一标识符 (ES6 new 增)
  • BigInt: 表示 big 整数 (ES11 new 增)

引用dataclass型

  • Object: objectclass型, includingarray, function, 日期etc.
// basicdataclass型
let num = 100;          // Number
let str = "Hello";       // String
let isTrue = true;       // Boolean
let empty = null;        // Null
let notDefined;         // Undefined
let sym = Symbol("id");  // Symbol
let big = 123n;          // BigInt

// 引用dataclass型
let obj = { name: "李四" };  // Object
let arr = [1, 2, 3];        // Array
let func = function() {};    // Function
let date = new Date();       // Date

2.3 运算符

JavaScriptsupport many 种运算符, including算术运算符, 比较运算符, 逻辑运算符, 赋值运算符etc..

算术运算符

let a = 10;
let b = 3;

console.log(a + b);  // 13 (加法) 
console.log(a - b);  // 7 (减法) 
console.log(a * b);  // 30 (乘法) 
console.log(a / b);  // 3.333... (除法) 
console.log(a % b);  // 1 (取余) 
console.log(a ** b); // 1000 (幂运算, ES7 new 增) 

比较运算符

let a = 5;
let b = "5";

console.log(a == b);   // true (宽松相etc., 会自动转换class型) 
console.log(a === b);  // false (严格相etc., 不会自动转换class型) 
console.log(a != b);   // false (宽松不etc.) 
console.log(a !== b);  // true (严格不etc.) 
console.log(a > b);    // false
console.log(a < b);    // false
console.log(a >= b);   // true
console.log(a <= b);   // true

逻辑运算符

let a = true;
let b = false;

console.log(a && b);  // false (逻辑 and ) 
console.log(a || b);  // true (逻辑 or ) 
console.log(!a);      // false (逻辑非) 

赋值运算符

let a = 10;

a += 5;   // etc.同于 a = a + 5
console.log(a);  // 15

a -= 3;   // etc.同于 a = a - 3
console.log(a);  // 12

a *= 2;   // etc.同于 a = a * 2
console.log(a);  // 24

a /= 4;   // etc.同于 a = a / 4
console.log(a);  // 6

2.4 控制语句

JavaScriptsupportcommon 控制语句, including条件语句 and 循环语句.

条件语句

// if...else语句
let age = 18;

if (age >= 18) {
    console.log("成年人");
} else {
    console.log("未成年人");
}

// if...else if...else语句
let score = 85;

if (score >= 90) {
    console.log("优秀");
} else if (score >= 80) {
    console.log("良 good ");
} else if (score >= 60) {
    console.log("及格");
} else {
    console.log("不及格");
}

// switch语句
let day = 3;
let dayName;

switch (day) {
    case 1:
        dayName = "星期一";
        break;
    case 2:
        dayName = "星期二";
        break;
    case 3:
        dayName = "星期三";
        break;
    case 4:
        dayName = "星期四";
        break;
    case 5:
        dayName = "星期五";
        break;
    case 6:
        dayName = "星期六";
        break;
    case 7:
        dayName = "星期日";
        break;
    default:
        dayName = "无效 天数";
}

console.log(dayName);  // 星期三

循环语句

// for循环
for (let i = 0; i < 5; i++) {
    console.log(i);  // 输出0, 1, 2, 3, 4
}

// while循环
let i = 0;
while (i < 5) {
    console.log(i);  // 输出0, 1, 2, 3, 4
    i++;
}

// do...while循环
let j = 0;
do {
    console.log(j);  // 输出0, 1, 2, 3, 4
    j++;
} while (j < 5);

// for...in循环 (遍历objectproperty) 
let person = {
    name: "张三",
    age: 25,
    job: "程序员"
};

for (let key in person) {
    console.log(key + ": " + person[key]);
}

// for...of循环 (遍历可iterationobject, such asarray, stringetc.) 
let arr = [1, 2, 3, 4, 5];

for (let value of arr) {
    console.log(value);  // 输出1, 2, 3, 4, 5
}

2.5 function

function is JavaScriptin 一etc.公民, 可以serving asparameter传递, 也可以serving asreturn value.

function声明

// function声明
function add(a, b) {
    return a + b;
}

let result = add(10, 20);
console.log(result);  // 30

function表达式

// function表达式
let multiply = function(a, b) {
    return a * b;
};

let result = multiply(10, 20);
console.log(result);  // 200

箭头function (ES6)

// 箭头function
let divide = (a, b) => a / b;

let result = divide(20, 4);
console.log(result);  // 5

// 箭头function ( many 行) 
let complex = (a, b) => {
    let sum = a + b;
    let product = a * b;
    return sum + product;
};

let result2 = complex(2, 3);
console.log(result2);  // 2+3 + 2*3 = 5 + 6 = 11

3. JavaScriptcode执行位置

JavaScriptcode可以放 in HTMLfile 不同位置.

3.1 in 联脚本

<!DOCTYPE html>
<html>
<body>
    <button onclick="alert('Hello World!')">点击我</button>
</body>
</html>

3.2 in 部脚本

<!DOCTYPE html>
<html>
<head>
    <title>JavaScriptexample</title>
    <script>
        // JavaScriptcode放 in headtagin
        function sayHello() {
            alert('Hello World!');
        }
    </script>
</head>
<body>
    <button onclick="sayHello()">点击我</button>
</body>
</html>

3.3 out 部脚本

<!DOCTYPE html>
<html>
<body>
    <button onclick="sayHello()">点击我</button>
    
    <!-- JavaScriptcode放 in  out 部filein -->
    <script src="script.js"></script>
</body>
</html>

其in, script.jsfile in 容 for :

function sayHello() {
    alert('Hello World!');
}

4. JavaScriptcomment

JavaScriptsupport单行comment and many 行comment.

// 这 is 单行comment

/*
这 is  many 行comment
可以跨越 many 行
*/

function add(a, b) {
    // 计算两个数  and 并返回结果
    return a + b; // 返回 and 
}

练习 1: variable and dataclass型

  1. 声明一个名 for name variable, 赋值 for 你 姓名.
  2. 声明一个名 for age variable, 赋值 for 你 年龄.
  3. 声明一个名 for isStudent variable, 赋值 for boolean值, 表示你 is 否 is 学生.
  4. usingconsole.log()输出这些variable 值.

练习 2: 运算符 and 控制语句

  1. 声明两个variablea and b, 分别赋值 for 10 and 5.
  2. using算术运算符计算它们 and , 差, 积, 商 and 余数, 并输出结果.
  3. using比较运算符比较它们 big small , 并输出结果.
  4. usingif...else语句判断a is 否 big 于b, such as果 is , 输出"a big 于b", 否则输出"a不 big 于b".

练习 3: function

  1. 声明一个名 for calculateArea function, 该function接受一个parameterradius, 用于计算圆 面积.
  2. using该function计算半径 for 5 圆 面积, 并输出结果.
  3. using箭头function重写该function, 并再次计算半径 for 5 圆 面积.