7个javascript实用小技巧

JavaScript1年前 (2023)更新 admin
2,212 0

每种编程语言都有一些“黑魔法”或者说小技巧,JS也不例外,大部分是借助ES6或者浏览器新特性实现。下面介绍的7个实用小技巧,相信其中有些你一定用过。

01.数组去重

const j = […new Set([1, 2, 3, 3])]
>> [1, 2, 3]

02.数组清洗

洗掉数组中一些无用的值,如0, undefined, null, false等

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

03.创建空对象

我们可以使用对象字面量{}来创建空对象,但这样创建的对象有隐式原型__proto__和一些对象方法比如常见的hasOwnProperty,下面这个方法可以创建一个纯对象。

let dict = Object.create(null);

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

该方法创建的对象没有任何的属性及方法

04.合并对象

JS中我们经常会有合并对象的需求,比如常见的给用传入配置覆盖默认配置,通过ES6扩展运算符就能快速实现。

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

05.设置函数必传参数

借助ES6支持的默认参数特性,我们可以将默认参数设置为一个执行抛出异常代码函数返回的值,这样当我们没有传参时就会抛出异常终止后面的代码运行。

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

06.解构别名

ES6中我们经常会使用对象结构获取其中的属性,但有时候会想重命名属性名,以避免和作用域中存在的变量名冲突,这时候可以为解构属性名添加别名。

const obj = { x: 1 };

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

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

07.获取查询字符串参数

以前获取URL中的字符串参数我们需要通过函数写正则匹配,现在通过URLSearchParamsAPI即可实现。

// 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的不断发展,很多语言层面上的不良特性都在逐渐移除或者改进,如今的一行ES6代码可能等于当年的几行代码。

拥抱JS的这些新变化意味着前端开发效率的不断提升,以及良好的编码体验。当然不管语言如何变化,我们总能在编程中总结一些小技巧来精简代码。

© 版权声明

相关文章

暂无评论

暂无评论...