10 个实用的 JavaScript 技巧

2025-05-28

10 个实用的 JavaScript 技巧

我一直在寻找提高效率的新方法。

而 JavaScript 总是充满着惊喜。

1. 将参数对象转换为数组。

参数对象是一个可在函数内部访问的类似数组的对象其中包含传递给该函数的参数的值。

但它不像其他数组,我们可以访问值并获取长度,但不能在其上使用其他数组方法。

幸运的是,我们可以将其转换为常规数组:

var argArray = Array.prototype.slice.call(arguments);

2. 对数组中的所有值求和。

我最初的直觉是使用循环,但那样太浪费了。

var numbers = [3, 5, 7, 2];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 17

3. 短路条件。

我们有以下代码:

if (hungry) {
    goToFridge();
}

我们可以通过使用带有函数的变量使其变得更短:

hungry && goToFridge()

4. 使用逻辑或作为条件。

我习惯在函数开始时声明变量,以避免在出现意外错误时导致变量未定义。

function doSomething(arg1){ 
    arg1 = arg1 || 32; // if it's not already set, arg1 will have 32 as a default value
}

5.逗号运算符。

逗号运算符 (,) 计算其每个操作数(从左到右)并返回最后一个操作数的值。

let x = 1;

x = (x++, x);

console.log(x);
// expected output: 2

x = (2, 3);

console.log(x);
// expected output: 3

6. 使用长度来调整数组的大小。

您可以调整数组大小或清空数组。

var array = [11, 12, 13, 14, 15];  
console.log(array.length); // 5  

array.length = 3;  
console.log(array.length); // 3  
console.log(array); // [11,12,13]

array.length = 0;  
console.log(array.length); // 0  
console.log(array); // []

7. 使用数组解构来交换值。

解构赋值语法是一种 JavaScript 表达式,它可以将数组中的值或对象的属性解包到不同的变量中。

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // -> 2
console.log(b) // -> 1

8. 从数组中随机排列元素。

我每天都在拖着脚步,
拖着脚步,拖着脚步

var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(list.sort(function() {
    return Math.random() - 0.5
})); 
// [4, 8, 2, 9, 1, 3, 6, 5, 7]

9. 属性名称可以是动态的。

您可以在声明对象之前分配动态属性。

const dynamic = 'color';
var item = {
    brand: 'Ford',
    [dynamic]: 'Blue'
}
console.log(item); 
// { brand: "Ford", color: "Blue" }

10. 过滤唯一值。

对于所有 ES6 粉丝来说,我们可以使用带有 Spread 运算符的 Set 对象创建一个仅包含唯一值的新数组。

const my_array = [1, 2, 2, 3, 3, 4, 5, 5]
const unique_array = [...new Set(my_array)];
console.log(unique_array); // [1, 2, 3, 4, 5]

结束语。

负责任远比高效重要。

您的网站需要在所有浏览器中运行。

您可以使用Endtest或其他类似工具来确保它确实如此。

那你呢?有什么 JavaScript 技巧可以分享吗?

文章来源:https://dev.to/zandershirley/10-practical-javascript-tricks-2b7h
PREV
轻松学习正则表达式
NEXT
在 Jest 中模拟 API 调用只需 3 个步骤