返回
为前端打造坚实基础:必备的手写代码集锦
前端
2023-10-28 10:29:28
写在前面
在当今快速发展的互联网世界中,前端技术的重要性与日俱增。前端工程师不仅需要掌握各种框架和工具,更需要具备扎实的手写代码能力。通过手写代码,前端工程师可以更深入地理解 JavaScript 语言的本质,并能灵活地解决各种开发难题。
本文将从 Array 篇
、Object + Function 篇
、ES6 Set、Map、class 篇
、Promise 篇
、常用函数
等五个方面,详细介绍前端工程师需要掌握的手写代码。这些代码涵盖了 JavaScript 的核心知识点,并结合实际应用场景,帮助您加深对 JavaScript 的理解。
Array 篇
数组是 JavaScript 中最常用的数据结构之一,也是前端工程师必须熟练掌握的核心知识点。
- 数组遍历:for 循环和 forEach 方法
// for 循环遍历数组
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// forEach 方法遍历数组
arr.forEach((item) => {
console.log(item);
});
- 数组排序:sort 方法和自定义比较函数
// 使用 sort 方法对数组进行升序排序
arr.sort();
// 使用 sort 方法对数组进行降序排序
arr.sort((a, b) => b - a);
// 自定义比较函数实现更复杂的排序规则
arr.sort((a, b) => {
if (a.name > b.name) {
return 1;
} else if (a.name < b.name) {
return -1;
} else {
return 0;
}
});
- 数组查找:indexOf、lastIndexOf 和 find 方法
// 使用 indexOf 方法查找数组中某个元素的索引
const index = arr.indexOf('apple');
// 使用 lastIndexOf 方法查找数组中某个元素的最后一个索引
const lastIndex = arr.lastIndexOf('apple');
// 使用 find 方法查找数组中满足某个条件的第一个元素
const apple = arr.find((item) => item === 'apple');
- 数组操作:push、pop、shift 和 unshift 方法
// 使用 push 方法向数组末尾添加元素
arr.push('banana');
// 使用 pop 方法从数组末尾删除元素
const lastItem = arr.pop();
// 使用 shift 方法从数组开头删除元素
const firstItem = arr.shift();
// 使用 unshift 方法向数组开头添加元素
arr.unshift('orange');
Object + Function 篇
对象和函数是 JavaScript 中的两大基石,也是前端工程师必须熟练掌握的核心知识点。
- 对象创建:字面量、构造函数和工厂函数
// 使用字面量创建对象
const person = {
name: 'John',
age: 30
};
// 使用构造函数创建对象
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person('John', 30);
// 使用工厂函数创建对象
function createPerson(name, age) {
return {
name: name,
age: age
};
}
const person = createPerson('John', 30);
- 对象属性访问:点语法和方括号表示法
// 使用点语法访问对象属性
person.name;
// 使用方括号表示法访问对象属性
person['name'];
- 对象方法调用:调用函数和使用箭头函数
// 调用对象方法
person.greet();
// 使用箭头函数定义对象方法
const person = {
name: 'John',
greet: () => {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet();
- 函数定义:函数声明和函数表达式
// 使用函数声明定义函数
function greet(name) {
console.log(`Hello, ${name}!`);
}
// 使用函数表达式定义函数
const greet = (name) => {
console.log(`Hello, ${name}!`);
};
ES6 Set、Map、class 篇
ES6 中引入的 Set、Map 和 class 等新特性极大地增强了 JavaScript 的表达力和灵活性。
- Set:创建和使用集合
// 创建 Set 集合
const set = new Set();
// 向 Set 集合中添加元素
set.add('apple');
set.add('banana');
set.add('orange');
// 从 Set 集合中删除元素
set.delete('apple');
// 检查 Set 集合中是否存在某个元素
set.has('banana');
// 获取 Set 集合中所有元素
for (const item of set) {
console.log(item);
}
- Map:创建和使用映射
// 创建 Map 映射
const map = new Map();
// 向 Map 映射中添加键值对
map.set('apple', 'red');
map.set('banana', 'yellow');
map.set('orange', 'orange');
// 从 Map 映射中获取值
map.get('apple');
// 检查 Map 映射中是否存在某个键
map.has('banana');
// 删除 Map 映射中的键值对
map.delete('orange');
// 遍历 Map 映射
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
- class:创建和使用类
// 创建类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
// 创建类实例
const person = new Person('John', 30);
// 调用类方法
person.greet();
Promise 篇
Promise 是 JavaScript 中用于处理异步操作的神器,也是前端工程师必须熟练掌握的核心知识点。
- Promise 的创建和使用
// 创建 Promise 对象
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
// 成功
resolve('success');
// 失败
reject('error');
}, 1000);
});
// 使用 then 方法处理 Promise 的成功结果
promise.then((result) => {
console.log(result);
});
// 使用 catch 方法处理 Promise 的失败结果
promise.catch((error) => {
console.log(error);
});
- Promise 的链式调用
promise.then((result) => {
// 处理成功结果并返回新的 Promise 对象
return new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
// 成功
resolve('new success');
// 失败
reject('new error');
}, 1000);
});
})
.then((newResult) => {
console.log(newResult);
})
.catch((error) => {
console.log(error);
});
常用函数
前端工程师在开发中经常会用到一些常用的函数,比如判断数据类型、类型转换、日期操作等。
- 判断数据类型
// 使用 typeof 运算符判断数据类型
console.log(typeof 'string'); // string
console.log(typeof 100); // number
console.log(typeof true); // boolean
console.log(typeof null); // object
console.log(typeof undefined); // undefined
- 类型转换
// 使用 Number() 函数将字符串转换为数字
const num = Number('100');
// 使用 String() 函数将数字转换为字符串
const str = String(100);
// 使用 Boolean() 函数将值转换为布尔值
const bool = Boolean(1);
- 日期操作
// 创建 Date 对象
const date = new Date();
// 获取当前日期
console.log(date.getDate());
// 获取当前月份
console.log(date.getMonth());
// 获取当前年份