7个有用JavaScript技巧

Just like every other programming language, JavaScript has dozens of tricks to accomplish both easy and difficult tasks. Some tricks are widely known while others are enough to blow your mind. Let's have a look at seven JavaScript tricks you can start using today!

就像其他所有编程语言一样,JavaScript具有许多技巧来完成简单和困难的任务。 一些技巧已广为人知,而其他一些技巧足以使您震惊。 让我们来看看您今天可以开始使用的七个JavaScript技巧!

获取数组的唯一值 (Get Unique Values of an Array)

Getting an array of unique values is probably easier than you think:

获取唯一值数组可能比您想象的要容易:

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

I love the mixture of rest expression and Set!

我喜欢休息表情和Set的混合体!

数组和布尔 (Array and Boolean)

Ever need to filter falsy values (0, undefined, null, false, etc.) out of an array? You may not have known this trick:

是否曾经需要从数组过滤出伪造的值 ( 0undefinednullfalse等)? 您可能不知道此技巧:

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

Just pass Boolean and all those falsy value go away!

只需传递Boolean ,所有那些虚假的值就会消失!

创建空对象 (Create Empty Objects)

Sure you can create an object that seems empty with {}, but that object still has a __proto__ and the usual hasOwnProperty and other object methods. There is a way, however, to create a pure "dictionary" object:

当然,您可以使用{}创建一个似乎为空的对象,但是该对象仍然具有__proto__以及通常的hasOwnProperty和其他对象方法。 但是,有一种方法可以创建一个纯“字典”对象

let dict = Object.create(null);

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

There are absolutely no keys or methods on that object that you don't put there!

没有放置在该对象上的键或方法绝对没有!

合并物件 (Merge Objects)

The need to merge multiple objects in JavaScript has been around forever, especially as we started creating classes and widgets with options:

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

Those three dots made the task so much easier!

这三个点使任务变得如此简单!

需要功能参数 (Require Function Parameters)

Being able to set default values for function arguments was an awesome addition to JavaScript, but check out this trick for requiring values be passed for a given argument:

能够为函数参数设置默认值是对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');

That's some next level validation and JavaScript usage!

这是一些下一级的验证和JavaScript的用法!

破坏别名 (Destructuring Aliases)

Destructuring is a very welcomed addition to JavaScript but sometimes we'd prefer to refer to those properties by another name, so we can take advantage of aliases:

销毁是JavaScript的一个非常受欢迎的附加功能,但是有时我们希望用另一个名称来引用这些属性,因此我们可以利用别名:

const obj = { x: 1 };

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

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

Useful for avoiding naming conflicts with existing variables!

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

获取查询字符串参数 (Get Query String Parameters)

For years we wrote gross regular expressions to get query string values but those days are gone -- enter the amazing URLSearchParams API:

多年以来,我们编写了粗糙的正则表达式来获取查询字符串值,但是日子已经一去不复返了–输入令人惊叹的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"

Much easier than we used to fight with!

比我们过去战斗容易得多!

JavaScript has changed so much over the years but my favorite part of JavaScript these days is the velocity in language improvements we're seeing. Despite the changing dynamic of JavaScript, we still need to employ a few decent tricks; keep these tricks in your toolbox for when you need them!

多年来,JavaScript发生了很大变化,但如今,我最喜欢JavaScript部分是我们看到的语言改进的速度。 尽管JavaScript的动态方式发生了变化,但我们仍然需要采用一些不错的技巧。 将这些技巧保存在工具箱中,以备需要时使用!

What are your favorite JavaScript tricks?

您最喜欢JavaScript技巧是什么?

翻译自: https://davidwalsh.name/javascript-tricks

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值