就如其他的编程语言一样, JavaScript 也具有许多技巧来完成简单和困难的任务. 一些技巧已广为人知, 而有一些技巧也会让你耳目一新. 让我们来看看今天可以开始使用的七个 JavaScript 技巧吧!
数组去重
使用 ES6 全新的数据结构即可简单实现.
var j = [...new Set([1, 2, 3, 3])]
输出: [1, 2, 3]
Set 的详细用法可以查看 ES6 入门 http://es6.ruanyifeng.com/#docs/set-map
数组和布尔值
当数组需要快速过滤掉一些为 false 的值 (0,undefined,false 等) 使, 一般是这样写:
- myArray
- .map(item => {
- // ...
- })
- // Get rid of bad values
- .filter(item => item);
可以使用 Boolean 更简洁地实现
- myArray
- .map(item => {
- // ...
- })
- // Get rid of bad values
- .filter(Boolean);
例如:
- console.log([1,0,null].filter(Boolean));
- // 输出:[1]
创建纯空对象
你一般会使用 {} 来创建一个空对象, 但是这个对象其实还是会有__proto__特性和 hasOwnProperty 方法以及其他方法的.
var o = {}
例如有一些对象方法:
但是创建一个纯 "字典" 对象, 可以这样实现:
- let dict = Object.create(null);
- // dict.__proto__ === "undefined"
- // 对象没有任何的属性及方法
合并对象
合并多个对象这个使用展开运算符 (...) 即可简单实现:
- 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}`)
- };
- // 没有传值, 抛出异常
- hello();
- // 抛出异常
- hello(undefined);
- // 校验通过
- hello(null);
- hello('David');
函数默认参数允许在没有值或 undefined 被传入时使用默认形参. 如果默认值是一个表达式, 那么这个表达式是惰性求值的, 即只有在用到的时候, 才会求值.
解构别名
- const obj = {
- x: 1
- };
- // 通过 {
- x
- } 获取 obj.x 值
- const {
- x
- } = obj;
- // 设置 obj.x 别名为 {
- otherName
- }
- const {
- x: otherName
- } = obj;
获取查询字符串参数
使用 URLSearchParamsAPI 可以轻松获取查询字符串各项的值:
- // Assuming "?post=1234&action=edit"
- var urlParams = new URLSearchParams(Windows.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"
- (完)
参考
原文链接 https://davidwalsh.name/javascript-tricks
默认参数
来源: https://www.cnblogs.com/GeniusLyzh/p/12355154.html