JavaScript 第2章 基本语法

第二部分:基本语法

第2章:基本语法

变量声明:let, const, var

变量声明

  • var:全局或函数级作用域,可重复声明同名变量。
  • let:块级作用域,不可重复声明同名变量。
  • const:块级作用域,声明常量,一旦赋值不可更改。

示例:

// 使用var声明变量
var x = 10;
if (true) {
    var x = 20; // 在整个作用域内都可以访问
}
console.log(x); // 输出20

// 使用let声明变量
let y = 10;
if (true) {
    let y = 20; // 仅在if块内可访问
}
console.log(y); // 输出10

// 使用const声明常量
const PI = 3.14;
// PI = 3.15; // 抛出错误:Assignment to constant variable.

数据类型:字符串、数字、布尔值、数组、对象

字符串

  • 字符串可以使用单引号或双引号包裹。
  • 使用模板字符串可以方便地拼接字符串。

示例:

let name = 'Alice';
let greeting = `Hello, ${name}!`; // 使用模板字符串
console.log(greeting); // 输出: Hello, Alice!

数字

  • 数字可以表示整数或浮点数。

示例:

let age = 25;
let pi = 3.14159;
console.log(age + pi); // 输出: 28.14159

布尔值

  • 布尔值有两个可能的值:true 和 false。

示例:

let isAdult = true;
console.log(isAdult); // 输出: true

数组

  • 数组用于存储多个值。

示例:

let fruits = ['apple', 'banana', 'orange'];
fruits.push('grape'); // 添加元素
console.log(fruits[0]); // 输出: apple
console.log(fruits.length); // 输出: 4

对象

  • 对象用于存储键值对。

示例:

let person = {
    name: 'Bob',
    age: 30,
    sayHello: function() {
        console.log(`Hello, my name is ${this.name}.`);
    }
};
person.sayHello(); // 输出: Hello, my name is Bob.

字面量与构造函数

字面量

  • 字面量是直接在代码中表示值的一种方式。
  • 字符串、数字、布尔值、数组、对象都可以使用字面量表示。

构造函数

  • 构造函数是一种特殊的函数,用于创建具有特定属性和方法的对象。

示例:

// 字面量表示
let literalPerson = { name: 'Charlie', age: 35 };

// 构造函数表示
function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        console.log(`Hi, I'm ${this.name} and I am ${this.age} years old.`);
    };
}
let constructedPerson = new Person('David', 40);
constructedPerson.greet(); // 输出: Hi, I'm David and I am 40 years old.

运算符:算术运算符、比较运算符、逻辑运算符

算术运算符

  • 常见的算术运算符包括:加 (+)、减 (-)、乘 (*)、除 (/)、模 (%)。

示例:

let a = 10;
let b = 5;
console.log(a + b); // 输出: 15
console.log(a - b); // 输出: 5
console.log(a * b); // 输出: 50
console.log(a / b); // 输出: 2
console.log(a % b); // 输出: 0

比较运算符

  • 比较运算符用来比较两个值,并返回一个布尔值。

示例:

let c = 10;
let d = 20;
console.log(c == d); // 输出: false
console.log(c != d); // 输出: true
console.log(c > d); // 输出: false
console.log(c < d); // 输出: true
console.log(c >= d); // 输出: false
console.log(c <= d); // 输出: true

逻辑运算符

  • 主要有逻辑与 (&&)、逻辑或 (||) 和逻辑非 (!)。

示例:

let e = true;
let f = false;
console.log(e && f); // 输出: false
console.log(e || f); // 输出: true
console.log(!e); // 输出: false

表达式与语句

表达式

  • 表达式是用来计算值的一组元素。

语句

  • 语句是执行某些操作的一组元素。

示例:

// 表达式
let result = 1 + 2;

// 语句
if (result > 2) {
    console.log('Result is greater than 2.');
} else {
    console.log('Result is not greater than 2.');
}

通过这些示例,读者可以更好地理解JavaScript的基本语法,并学会如何在实际的业务场景中应用这些语法。例如,在创建用户界面时,可以使用变量和对象来管理用户数据;在处理用户输入时,可以利用条件语句和循环来实现逻辑判断和数据处理。

在这里插入图片描述

我们会继续添加更多案例来帮助读者更好地理解和应用JavaScript的基本语法。以下是一些新的案例,涵盖了常见的业务应用场景:

第二部分:基本语法

第2章:基本语法
变量声明:let, const, var

示例:变量作用域与提升

console.log(x); // 输出: undefined
console.log(y); // 抛出ReferenceError,因为let声明的变量不会被提升
var x = 10;
let y = 20;

示例:常量的使用

const PI = 3.14159;
console.log(PI); // 输出: 3.14159
// PI = 3.15; // 抛出TypeError,因为const声明的变量不可重新赋值

示例:变量在循环中的作用域

for (let i = 0; i < 5; i++) {
    console.log(i); // 输出: 0, 1, 2, 3, 4
}
// console.log(i); // 抛出ReferenceError,因为let声明的i只在循环体内部有效
数据类型:字符串、数字、布尔值、数组、对象

示例:字符串操作

let name = 'Alice';
let message = `Hello, ${name}!`;
console.log(message); // 输出: Hello, Alice!

// 字符串长度
console.log(name.length); // 输出: 5

// 字符串截取
console.log(name.substring(1, 3)); // 输出: li

示例:数字操作

let num1 = 10;
let num2 = 5.5;

// 四舍五入
console.log(Math.round(num2)); // 输出: 6

// 保留两位小数
console.log(num2.toFixed(2)); // 输出: "5.50"

// 进行数学运算
console.log(num1 + num2); // 输出: 15.5
console.log(num1 * num2); // 输出: 55

示例:布尔值的使用

let isLoggedIn = true;
let isStudent = false;

// 条件判断
if (isLoggedIn) {
    console.log('用户已登录');
} else {
    console.log('用户未登录');
}

// 布尔值转换
console.log(Boolean(0)); // 输出: false
console.log(Boolean('')); // 输出: false

示例:数组操作

let fruits = ['apple', 'banana', 'orange'];

// 添加元素
fruits.push('grape');
console.log(fruits); // 输出: ['apple', 'banana', 'orange', 'grape']

// 移除元素
fruits.pop();
console.log(fruits); // 输出: ['apple', 'banana', 'orange']

// 遍历数组
fruits.forEach((fruit, index) => {
    console.log(`${index}: ${fruit}`);
});
// 输出:
// 0: apple
// 1: banana
// 2: orange

示例:对象操作

let person = {
    name: 'Bob',
    age: 30,
    hobbies: ['reading', 'coding'],
    greet: function() {
        console.log(`Hello, my name is ${this.name}.`);
    }
};

// 访问对象属性
console.log(person.name); // 输出: Bob
console.log(person['age']); // 输出: 30

// 修改对象属性
person.age = 31;
console.log(person.age); // 输出: 31

// 调用对象方法
person.greet(); // 输出: Hello, my name is Bob.

// 遍历对象属性
Object.keys(person).forEach(key => {
    console.log(`${key}: ${person[key]}`);
});
// 输出:
// name: Bob
// age: 31
// hobbies: reading,coding
// greet: [Function: greet]
字面量与构造函数

示例:使用构造函数创建对象

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.describe = function() {
        console.log(`${this.make} ${this.model} from ${this.year}`);
    };
}

let myCar = new Car('Toyota', 'Corolla', 2020);
myCar.describe(); // 输出: Toyota Corolla from 2020
运算符:算术运算符、比较运算符、逻辑运算符

示例:使用算术运算符

let a = 10;
let b = 5;

console.log(a + b); // 输出: 15
console.log(a - b); // 输出: 5
console.log(a * b); // 输出: 50
console.log(a / b); // 输出: 2
console.log(a % b); // 输出: 0
console.log(++a); // 输出: 11
console.log(--b); // 输出: 4

示例:使用比较运算符

let c = 10;
let d = 20;

console.log(c == d); // 输出: false
console.log(c != d); // 输出: true
console.log(c > d); // 输出: false
console.log(c < d); // 输出: true
console.log(c >= d); // 输出: false
console.log(c <= d); // 输出: true
console.log(c === '10'); // 输出: false

示例:使用逻辑运算符

let e = true;
let f = false;

console.log(e && f); // 输出: false
console.log(e || f); // 输出: true
console.log(!e); // 输出: false
console.log(!(e && f)); // 输出: true
console.log((e && f) || !f); // 输出: true
表达式与语句

示例:复合赋值运算符

let x = 10;
x += 5; // 等价于 x = x + 5;
console.log(x); // 输出: 15

x *= 2; // 等价于 x = x * 2;
console.log(x); // 输出: 30

示例:条件(三元)运算符

let score = 85;
let grade = score >= 60 ? '及格' : '不及格';
console.log(grade); // 输出: 及格

let bonus = score > 90 ? 100 : (score > 80 ? 50 : 0);
console.log(bonus); // 输出: 50

示例:switch 语句

let dayOfWeek = 'Wednesday';

switch (dayOfWeek) {
    case 'Monday':
        console.log('Today is Monday.');
        break;
    case 'Tuesday':
        console.log('Today is Tuesday.');
        break;
    case 'Wednesday':
        console.log('Today is Wednesday.');
        break;
    default:
        console.log('Today is not one of the first three days.');
}

// 输出: Today is Wednesday.

通过这些示例,读者可以进一步理解JavaScript中的变量声明、数据类型、运算符以及语句的使用,并且能够将这些基本概念应用于实际的业务场景中,如用户信息管理、表单验证、数据处理等。

在这里插入图片描述

我们继续增加一些示例,以便更全面地展示JavaScript在实际业务场景中的应用。这次我们将关注一些常见的业务需求,如数据验证、表单处理、动态更新UI等。

第二部分:基本语法

第2章:基本语法
字面量与构造函数

示例:构造函数与继承

function Vehicle(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

Vehicle.prototype.describe = function() {
    console.log(`${this.year} ${this.make} ${this.model}`);
};

function Car(make, model, year, doors) {
    Vehicle.call(this, make, model, year); // 调用父类构造函数
    this.doors = doors;
}

// 继承Vehicle
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;

let myCar = new Car('Toyota', 'Corolla', 2020, 4);
myCar.describe(); // 输出: 2020 Toyota Corolla
console.log(myCar.doors); // 输出: 4
运算符:算术运算符、比较运算符、逻辑运算符

示例:位运算符

let a = 5; // 二进制形式为 0101
let b = 3; // 二进制形式为 0011

console.log(a & b); // 按位与运算,输出: 1 (二进制0001)
console.log(a | b); // 按位或运算,输出: 7 (二进制0111)
console.log(a ^ b); // 按位异或运算,输出: 6 (二进制0110)
console.log(~a); // 按位非运算,输出: -6 (二进制...11111010)
console.log(a << 1); // 左移运算,输出: 10 (二进制1010)
console.log(a >> 1); // 右移运算,输出: 2 (二进制0010)

示例:逻辑运算符的短路求值

let user = {
    name: 'Alice',
    isAdmin: false
};

function adminAccess(user) {
    return user.isAdmin && console.log(user.name);
}

adminAccess(user); // 输出: undefined,因为逻辑与左侧为false,右侧不会执行
表达式与语句

示例:使用闭包保护变量

function createCounter() {
    let count = 0; // 私有变量
    return {
        increment: function() {
            count++;
            return count;
        },
        decrement: function() {
            count--;
            return count;
        },
        getCount: function() {
            return count;
        }
    };
}

let counter = createCounter();
console.log(counter.increment()); // 输出: 1
console.log(counter.decrement()); // 输出: 0
console.log(counter.getCount()); // 输出: 0
示例:动态生成HTML元素

示例:动态生成表格

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Table Generation</title>
</head>
<body>
    <table id="dataTable"></table>
    <script>
        let tableData = [
            { name: 'Alice', age: 30 },
            { name: 'Bob', age: 25 },
            { name: 'Carol', age: 28 }
        ];

        function generateTable(tableData) {
            let table = document.getElementById('dataTable');

            // 创建表头
            let headerRow = document.createElement('tr');
            let headers = ['Name', 'Age'];
            headers.forEach(headerText => {
                let th = document.createElement('th');
                th.textContent = headerText;
                headerRow.appendChild(th);
            });
            table.appendChild(headerRow);

            // 创建数据行
            tableData.forEach(rowData => {
                let row = document.createElement('tr');
                Object.values(rowData).forEach(value => {
                    let cell = document.createElement('td');
                    cell.textContent = value;
                    row.appendChild(cell);
                });
                table.appendChild(row);
            });
        }

        generateTable(tableData);
    </script>
</body>
</html>
示例:使用事件监听器

示例:按钮点击事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Button Click Event Listener</title>
</head>
<body>
    <button id="clickButton">Click Me!</button>
    <p id="message"></p>
    <script>
        let button = document.getElementById('clickButton');
        let message = document.getElementById('message');

        button.addEventListener('click', function() {
            message.textContent = 'Button was clicked!';
        });
    </script>
</body>
</html>
示例:表单验证

示例:表单输入验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Validation</title>
</head>
<body>
    <form id="registrationForm">
        <label for="username">Username:</label>
        <input type="text" id="username" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" id="password" required>
        <br>
        <button type="submit">Submit</button>
    </form>
    <p id="validationMessage"></p>
    <script>
        let form = document.getElementById('registrationForm');
        let usernameInput = document.getElementById('username');
        let passwordInput = document.getElementById('password');
        let message = document.getElementById('validationMessage');

        form.addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            if (usernameInput.value.trim() === '') {
                message.textContent = 'Username cannot be empty.';
                return;
            }

            if (passwordInput.value.trim() === '') {
                message.textContent = 'Password cannot be empty.';
                return;
            }

            // 如果验证通过,可以继续处理表单数据
            message.textContent = 'Form submitted successfully!';
        });
    </script>
</body>
</html>

在这里插入图片描述

示例:日期和时间

示例:显示当前时间和日期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Current Date and Time</title>
</head>
<body>
    <p id="currentTime"></p>
    <script>
        function displayCurrentDateTime() {
            let now = new Date();
            let dateString = now.toLocaleString();
            document.getElementById('currentTime').textContent = "Current time: " + dateString;
        }

        displayCurrentDateTime(); // 页面加载时立即显示时间
    </script>
</body>
</html>

在这里插入图片描述

通过这些示例,读者可以更好地理解如何使用JavaScript进行数据处理、事件处理、动态生成HTML元素等操作,并将这些技术应用到实际的Web开发项目中。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值