这篇文章将为大家详细讲解有关好用的JavaScript技巧有哪些,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
数组去重
数组去重可能比您想象的更容易:
var j = [...new Set([1, 2, 3, 4, 4])]
>> [1, 2, 3, 4]
很简单有木有!
过滤掉falsy值
是否需要从数组中过滤出falsy值(0,undefined,null,false等)? 你可能不知道还有这个技巧:
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
这种方式创建的对象就很纯粹,没有任何属性和对象,非常干净。
合并对象
在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",
}
*/
这三个点(...)使任务变得更加容易!
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技巧有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。