【译】分享7个好用的JavaScript技巧

就像全部其余编程语言同样,JavaScript也有许多技巧能够完成简单和困难的任务。 一些技巧广为人知,而其余技巧则足以让你大吃一惊。 让咱们来看看你今天就能够开始使用的七个JavaScript技巧吧!javascript

原文连接:davidwalsh.name/javascript-…java

数组去重

数组去重可能比您想象的更容易:git

var j = [...new Set([1, 2, 3, 4, 4])]
>> [1, 2, 3, 4]
复制代码

很简单有木有!github

过滤掉falsy值

是否须要从数组中过滤出falsy值(0undefinednullfalse等)? 你可能不知道还有这个技巧:正则表达式

let res = [1,2,3,4,0,undefined,null,false,''].filter(Boolean);
>> 1,2,3,4
复制代码

建立空对象

您可使用{ }建立一个看似空的对象,但该对象仍然具备__proto__和一般的hasOwnProperty以及其余对象方法。 可是,有一种方法能够建立一个纯粹的“字典”对象:编程

let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them
复制代码

这种方式建立的对象就很纯粹,没有任何属性和对象,很是干净。api

合并对象

在JavaScript中合并多个对象的需求已经存在,尤为是当咱们开始使用选项建立类和小部件时:数组

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const attributes = { handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' };

const summary = {...person, ...tools, ...attributes};
/* Object { "computer": "Mac", "editor": "Atom", "eyes": "Blue", "gender": "Male", "hair": "Brown", "handsomeness": "Extreme", "name": "David Walsh", } */
复制代码

这三个点(...)使任务变得更加容易!app

Require函数参数

可以为函数参数设置默认值是JavaScript的一个很棒的补充,可是请查看这个技巧,要求为给定的参数传递值:编程语言

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// This will throw an error because no name is provided
hello();

// This will also throw an error
hello(undefined);

// These are good!
hello(null);
hello('David');
复制代码

解构添加别名

解构是JavaScript的一个很是受欢迎的补充,但有时咱们更喜欢用其余名称来引用这些属性,因此咱们能够利用别名:

const obj = { x: 1 };

// Grabs obj.x as { x }
const { x } = obj;

// Grabs obj.x as { otherName }
const { x: otherName } = obj;
复制代码

有助于避免与现有变量的命名冲突!

获取查询字符串参数

获取url里面的参数值或者追加查询字符串,在这以前,咱们通常经过正则表达式来获取查询字符串值,然而如今有一个新的api,具体详情能够查看这里,可让咱们以很简单的方式去处理url。

好比如今咱们有这样一个url,"?post=1234&action=edit",咱们能够利用下面的技巧来处理这个url。

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
复制代码

比咱们过去用的容易多了!

多年来JavaScript已经发生了很大的变化,可是我最喜欢的JavaScript部分是咱们所看到的语言改进的速度。 尽管JavaScript的动态不断变化,咱们仍然须要采用一些不错的技巧; 将这些技巧保存在工具箱中,以便在须要时使用!

那你最喜欢的JavaScript技巧是什么?

若是以为文章对你有些许帮助,欢迎在个人GitHub博客点赞和关注,感激涕零!

相关文章
相关标签/搜索