16

10 个实用的 JS 技巧

 3 years ago
source link: https://www.infoq.cn/article/fgeB0Bu3jpAzmba9ro3x
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

将 arguments 对象转换为数组

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

与其他数组不同,这里我们可以访问值并获得长度(length),但是不能在其上使用其他数组方法。

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

复制代码

varargArray =Array.prototype.slice.call(arguments);

对数组中的所有值求和

我一开始想到的是使用一个循环,但是那样会很浪费。

复制代码

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

条件短路

我们有以下代码:

复制代码

if(hungry){
goToFridge();
}

我们可以进一步简化代码,同时使用变量和函数:

复制代码

hungry&&goToFridge()

对条件使用或(OR)逻辑

我以前在函数开始时声明变量,只是为了避免在出现意外错误时遇到 undefined。

复制代码

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

逗号运算符

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

复制代码

letx= 1;
x= (x++,x);
console.log(x);
// expectedoutput: 2
x= (2, 3);
console.log(x);
// expectedoutput: 3

使用 length 调整数组大小

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

复制代码

vararray= [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);// []

使用数组解构来交换值

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

复制代码

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

随机排列数组中的元素

复制代码

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

属性名称可以是动态的

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

复制代码

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

过滤唯一值

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

复制代码

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

总结

  • 履行好自己的责任比提升效率要重要的多。

  • 你的网站需要兼容 所有浏览器。

  • 你可以使用 Endtest 或其他类似工具来确保兼容性。

你还有其他 JavaScript 技巧或窍门要分享吗?

英文原文

10 Practical JavaScript Tricks


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK