学习如何存储和使用数据
变量是用于存储数据的容器。可以把变量想象成一个带标签的盒子,用来存放不同的值。
let name = 'Alice'; // 存储字符串
let age = 25; // 存储数字
let isStudent = true; // 存储布尔值JavaScript 有三种声明变量的方式:
声明块级作用域的变量,可以重新赋值。
let name = 'Alice';
name = 'Bob'; // 可以修改
let count = 0;
count = count + 1; // 可以修改声明常量,值不能被重新赋值。
const PI = 3.14159;
// PI = 3.14; // 错误!不能修改
const birthYear = 1990;
// birthYear = 1991; // 错误!旧的声明方式,有作用域问题,不推荐使用。
var oldWay = 'Not recommended';
// 推荐使用 let 或 const 代替JavaScript 有 7 种基本数据类型(原始类型):
整数和小数都是 Number 类型。
let age = 25; // 整数
let price = 99.99; // 小数
let negative = -10; // 负数
let billion = 1e9; // 科学计数法:1,000,000,000用引号包裹的文本。
let name = 'Alice'; // 单引号
let greeting = "Hello"; // 双引号
let message = `Hi, ${name}`; // 模板字符串(反引号)只有两个值:true 或 false。
let isStudent = true;
let hasLicense = false;
let isAdult = age >= 18; // 比较结果是布尔值变量已声明但未赋值。
let x;
console.log(x); // undefined表示"无"、"空"或"值未知"。
let user = null; // 明确表示没有值创建唯一的标识符(高级用法)。
let id = Symbol('id');表示任意大的整数。
let bigNumber = 1234567890123456789012345678901234567890n;let age = 25;let name = 'Alice';let isTrue = true;let x;使用 typeof 可以检查变量的数据类型。
console.log(typeof 42); // "number"
console.log(typeof 'Hello'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (这是历史遗留bug)
console.log(typeof Symbol('id')); // "symbol"let num = 123;
let str = String(num); // "123"
let str2 = num.toString(); // "123"
let str3 = num + ''; // "123" (隐式转换)let str = '123';
let num = Number(str); // 123
let num2 = parseInt(str); // 123 (整数)
let num3 = parseFloat('3.14'); // 3.14 (小数)
let num4 = +str; // 123 (隐式转换)Boolean(1); // true
Boolean(0); // false
Boolean('hello'); // true
Boolean(''); // false
Boolean(null); // false
Boolean(undefined); // falselet firstName = 'Alice';
let lastName = 'Smith';
let fullName = firstName + ' ' + lastName; // "Alice Smith"let name = 'Alice';
let age = 25;
let message = `我叫 ${name},今年 ${age} 岁`;
// "我叫 Alice,今年 25 岁"
// 支持表达式
let result = `2 + 3 = ${2 + 3}`; // "2 + 3 = 5"let text = 'Hello, World!';
text.length; // 13 (长度)
text.toUpperCase(); // "HELLO, WORLD!"
text.toLowerCase(); // "hello, world!"
text.includes('World'); // true
text.indexOf('World'); // 7
text.slice(0, 5); // "Hello"
text.replace('World', 'JS'); // "Hello, JS!"输入不同的值,查看其数据类型:
尝试输入:
使用模板字符串创建个人介绍: