返回

5 分钟掌握 9 个犀利而简单的 JavaScript 技巧

前端

作为一名 JavaScript 开发者,掌握一些简洁而实用的技巧可以极大地提高你的编码效率和开发体验。在这篇文章中,我们将分享 9 个这样的技巧,涵盖数组操作、字符串处理、函数使用等方面,帮助你快速掌握 JavaScript 的精髓,在开发过程中如虎添翼。

1. 巧用数组的 length 属性来截取数组

const arr = [1, 2, 3, 4, 5];
arr.length = 3; // 截取前三个元素
console.log(arr); // 输出:[1, 2, 3]

2. 使用数组的 slice() 方法提取子数组

const arr = [1, 2, 3, 4, 5];
const subArr = arr.slice(2, 4); // 提取索引 2 到 3 之间的元素
console.log(subArr); // 输出:[3, 4]

3. 巧妙利用字符串的 charAt() 方法来提取单个字符

const str = "Hello World";
const char = str.charAt(6); // 提取索引 6 处的字符
console.log(char); // 输出:"W"

4. 通过字符串的 indexOf() 和 lastIndexOf() 方法来查找子字符串

const str = "Hello World";
const index1 = str.indexOf("llo"); // 查找第一个 "llo" 子字符串的索引
const index2 = str.lastIndexOf("llo"); // 查找最后一个 "llo" 子字符串的索引
console.log(index1, index2); // 输出:2, 7

5. 使用字符串的 split() 方法来拆分字符串

const str = "Hello, World!";
const arr = str.split(","); // 以逗号作为分隔符拆分字符串
console.log(arr); // 输出:["Hello", " World!"]

6. 利用函数的 rest 参数来收集剩余参数

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 输出:15

7. 使用箭头函数来简化函数定义

const double = (num) => num * 2;
console.log(double(5)); // 输出:10

8. 利用三元运算符来实现条件判断

const isEven = (num) => (num % 2 === 0) ? "Even" : "Odd";
console.log(isEven(4)); // 输出:"Even"

9. 巧用 for...of 循环来遍历数组或对象

const arr = [1, 2, 3, 4, 5];
for (const num of arr) {
  console.log(num); // 输出:1, 2, 3, 4, 5
}