jrainlau / blog-articles

My personal blog.
https://jrain.vercel.app
40 stars 11 forks source link

【译】7个有用的 javascript 技巧 #2

Open jrainlau opened 5 years ago

jrainlau commented 5 years ago

image

原文链接: https://davidwalsh.name/javascript-tricks

和所有其他的编程语言一样,JS拥有着许多能够胜任简单或复杂功能的小技巧。有些小技巧足够让你大吃一惊。让我们一起来见识一下下面的7个JS小技巧,并立刻用起来吧!

数组去重

数组去重往往比你想象的要简单:

var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]

我爱结构运算符和 Set 的组合。

数组和布尔值

需要过滤掉数组中的非真值(0, undefined, null, false等等)?你可能不知道这个技巧:

myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);

只需要传入 Boolean,这样所有的非真值都会被过滤掉。

建立空对象

你可以通过 {} 新建一个对象,但这个对象依然包含 __proto__hasOwnProperty 等其他属性/方法。但是,你依然可以新建一个纯空对象:

let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them

这个对象完全不包含任何的属性和方法。

合并对象

在 JS 中合并多个对象是永恒的需求,尤其是在我们要撰写带设置项的类和组件的时候:

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",
}
*/

这些“点点点”让事情都变得简单了许多!

函数中的必传参数

允许写入默认参数是 JS 中的一大进步,但也请了解一下让默认参数变成必传参数的办法:

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');

这是一种更深层次的校验方法。

解构参数别名

参数解构是 JS 中非常受欢迎的一个功能,但有的时候我们希望可以赋予解构参数一个别名。我们可以这么做:

const obj = { x: 1 };

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

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

这在解决命名冲突的时候非常有用。

获取URL搜索参数

多年以来,我们写了许多正则表达式去获取 URL 当中的参数,但这些日子即将一去不返——因为我们有了 URLSearchParams API:

// 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"

比我们以前的做法都要简单多了!