Js基础扫盲
在日常的前端开发中,JavaScript无疑是核心技术之一。JavaScript语言的灵活性和表现力,让它在各种前端场景下展现出惊人的活力和创造力。JavaScript的每一个特性都可以用来解锁前端的新姿态,恰当运用这些技巧,不仅可以提高代码的效率,还能令阅读者和使用者眼前一亮。
以下便是JavaScript(JS)中值得关注的30个用法,每个用法均有示例代码进行展示,以期能让代码效率和可读性得到提升。
1. 默认参数值
在ES6以前,若函数参数未传值则默认为 undefined
,但现在可以设置默认参数值。
1function greeting(name = "Anonymous") {
2 return `Hello, ${name}!`;
3}
4console.log(greeting("Alice")); // "Hello, Alice!"
5console.log(greeting()); // "Hello, Anonymous!"
6
2. 模板字符串
用反引号(
)和
${}`,可以轻松拼接字符串和变量。
1const user = 'Jane';
2console.log(`Hi, ${user}!`); // "Hi, Jane!"
3
3. 多行字符串
使用反引号,可直接创建多行字符串。
1const multiLine = `This is a string
2that spans across
3multiple lines.`;
4console.log(multiLine);
5
4. 解构赋值
快速提取数组或对象中的值。
1const [a, b] = [1, 2];
2const { x, y } = { x: 10, y: 20 };
3console.log(a, b); // 1 2
4console.log(x, y); // 10 20
5
5. 展开运算符
用于数组或对象中创建副本或合并。
1const numbers = [1, 2, 3];
2const newNumbers = [...numbers, 4, 5];
3console.log(newNumbers); // [1, 2, 3, 4, 5]
4
6. 剩余参数
函数可以接受不定数量的参数,作为一个数组。
1function sum(...args) {
2 return args.reduce((total, current) => total + current, 0);
3}
4console.log(sum(1, 2, 3)); // 6
5
7. 箭头函数
更简洁的函数写法,自动绑定上下文 this
。
1const add = (a, b) => a + b;
2console.log(add(2, 3)); // 5
3
8. Promise 和异步
处理异步操作,支持链式调用。
1const fetchData = () => new Promise(resolve => setTimeout(() => resolve("Data"), 1000));
2fetchData().then(data => console.log(data)); // "Data"
3
9. Async/Await
使异步代码看起来更像同步代码。
1const fetchData = async () => {
2 const data = await new Promise(resolve => setTimeout(() => resolve("Data"), 1000));
3 console.log(data);
4};
5fetchData();
6
10. 对象属性简写
创建对象时,若键和变量名相同,可省略键。
1const name = "Alice";
2const age = 25;
3const user = { name, age };
4console.log(user); // { name: "Alice", age: 25 }
5
11. 计算属性名
在对象字面量中使用表达式作为属性名。
1const propName = "name";
2const user = {
3 [propName]: "Alice",
4};
5console.log(user.name); // "Alice"
6
12. 函数参数解构
直接在参数位置上解构对象或数组。
1function greet({ name, age }) {
2 console.log(`Hello, my name is ${name} and I'm ${age} years old.`);
3}
4greet({ name: "Alice", age: 30 });
5
13. 对象方法简写
对象中的函数可以省略 function
关键字。
1const calculator = {
2 add(a, b) {
3 return a + b;
4 },
5};
6console.log(calculator.add(2, 3)); // 5
7
14. 导入/导出模块
模块化JavaScript代码,让结构更清晰。
1// math.js
2export function add(a, b) { return a + b; }
3
4// main.js
5import { add } from './math.js';
6console.log(add(2, 3)); // 5
7
15. 类与构造函数
ES6引入了类的概念,使得面向对象编程更为直观。
1class Person {
2 constructor(name, age) {
3 this.name = name;
4 this.age = age;
5 }
6
7 greet() {
8 console.log(`Hello, my name is ${this.name}!`);
9 }
10}
11
12const person = new Person('Alice', 30);
13person.greet(); // "Hello, my name is Alice!"
14
16. 类的继承
类可以通过 extends
关键字继承其他类。
1class Animal {
2 constructor(name) {
3 this.name = name;
4 }
5 speak() {
6 console.log(`${this.name} makes a noise.`);
7 }
8}
9
10class Dog extends Animal {
11 constructor(name) {
12 super(name);
13 }
14 speak() {
15 console.log(`${this.name} barks.`);
16 }
17}
18
19const dog = new Dog('Rex');
20dog.speak(); // "Rex barks."
21
17. Set集合
用于创建无重复值的集合。
1const mySet = new Set([1, 2, 3, 2, 1]);
2console.log(mySet); // Set {1, 2, 3}
3
18. Map映射
类似于对象,但键的范围不限于字符串。
1const myMap = new Map();
2myMap.set('a', 1);
3myMap.set('b', 2);
4console.log(myMap.get('a')); // 1
5
19. Array.from
将类数组或可迭代对象转换为数组。
1const nodeList = document.querySelectorAll('div');
2const nodeArray = Array.from(nodeList);
3console.log(nodeArray); // [div, div, ...]
4
20. Array.find & findIndex
查找数组中满足条件的第一个元素及其索引。
1const numbers = [5, 12, 8, 130, 44];
2const found = numbers.find(number => number > 10);
3console.log(found); // 12
4
21. 对象的entries方法
返回一个对象所有的键值对数组。
1const user = { name: 'Alice', age: 25 };
2const entries = Object.entries(user);
3console.log(entries); // [["name", "Alice"], ["age", 25]]
4
22. 对象的keys和values方法
分别获取对象的所有键或所有值。
1const user = { name: 'Alice', age: 25 };
2const keys = Object.keys(user);
3const values = Object.values(user);
4console.log(keys); // ["name", "age"]
5console.log(values); // ["Alice", 25]
6
23. 对象的fromEntries方法
将键值对列表转换为对象。
1const entries = [['name', 'Alice'], ['age', 25]];
2const user = Object.fromEntries(entries);
3console.log(user); // { name: "Alice", age: 25 }
4
24. 对象和数组的深拷贝
使用JSON方法进行对象和数组的深拷贝。
1const user = { name: 'Alice', age: 25 };
2const userCopy = JSON.parse(JSON.stringify(user));
3console.log(userCopy); // { name: "Alice", age: 25 }
4
25. 可选链操作符
安全地访问深层次对象属性,避免引起错误。
1const user = { name: 'Alice', address: { city: 'Wonderland' } };
2console.log(user.address?.city); // "Wonderland"
3console.log(user.address?.postcode); // undefined
4
26. 空值合并操作符
在左侧操作数为 null
或 undefined
时,返回右侧操作数。
1const nullValue = null;
2const defaultValue = nullValue ?? 'default';
3console.log(defaultValue); // "default"
4
27. Symbol类型
创建唯一标识符,用于对象属性以避免冲突。
1const symbol = Symbol('description');
2console.log(symbol); // Symbol(description)
3
28. for...of 循环
用于遍历可迭代对象(如数组、Map、Set等)。
1const numbers = [1, 2, 3];
2for (const number of numbers) {
3 console.log(number);
4}
5// 1
6// 2
7// 3
8
29. for...in 循环
遍历对象的自身和继承的可枚举属性。
1const user = { name: 'Alice', age: 25 };
2for (const key in user) {
3 if (user.hasOwnProperty(key)) {
4 console.log(`${key}: ${user[key]}`);
5 }
6}
7// "name: Alice"
8// "age: 25"
9
30. strict模式
可通过"use strict"指令开启严格模式,提高代码的严谨性。
1'use strict';
2let undefinedVariable; // 未定义变量会抛出错误
3