article
article copied to clipboard
7 Useful JavaScript Tricks
原文地址: https://davidwalsh.name/javascript-tricks
原文作者: David Walsh
就像其他编程语言一样,JavaScript也有许多技巧可以完成简单或困难的任务。一些技巧广为人知,而一些技巧则足以让你大吃一惊,今天让我们来看看你可以开始使用的七个JavaScript技巧吧。
Get Unique Values of an Array
获取一系列唯一的值可能比你想象中的要简单:
var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]
Array and Boolean
是否需要从数组中过滤一些值,比如 false,null等,也许你可能不知道这个技巧:
f.filter(Boolean)
Create Empty Objects
当你可以使用 {} 创建一个看起来是空的空对象,但是它仍然具备 __proto__ 以及一些其他方法,但是有一种方法可以创建一个纯粹的空对象:
let dict = Object.create(null);
// dict.__proto__ === "undefined"
// No object properties exist until you add them
Merge Objects
在 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};
Require Function Parameters
能够为函数参数设置默认值是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');
Destructuring Aliases
解构是JavaScript的一个非常受欢迎的补充,但有时我们更喜欢用其他名称来引用这些属性,所以我们可以利用别名:
const obj = { x: 1 };
// Grabs obj.x as { x }
const { x } = obj;
// Grabs obj.x as { otherName }
const { x: otherName } = obj;
Get Query String Parameters
多年来,我们编写了大量的正则表达式来获取查询字符串值,但那些日子已经过去了,让我们来看看 URLSearchParams API
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技巧是什么?