URLSearchParams等方便操作的方法

数组去重
var arr = [1, 2, 3, 3, 4];
console.log(…new Set(arr))
>> [1, 2, 3, 4]
数组和布尔
有时我们需要过滤数组中值为 false 的值. 例如(0, undefined, null, false), 你可能不知道这样的技巧

var myArray = [1, 0 , undefined, null, false];
myArray.filter(Boolean);

[1]
是不是很简单, 只需要传入一个 Boolean 函数即可.

创建一个空对象
有时我们需要创建一个纯净的对象, 不包含什么原型链等等. 一般创建空对象最直接方式通过字面量 {}, 但这个对象中依然存在 proto 属性来指向 Object.prototype 等等.

let dict = Object.create(null);

dict.__proto__ === "undefined" 

合并对象
在JavaScript中合并多个对象的需求一直存在, 比如在传参时需要把表单参数和分页参数进行合并后在传递给后端

const page = {
    current: 1,
    pageSize: 10
}

const form = {
    name: "",
    sex: ""
}

const params = {...form, ...page};

/*
    {
        name: "",
        sex: "",
        current: 1,
        pageSize: 10
    }
*

利用ES6提供的扩展运算符让对象合并变得很简单.

函数参数必须
ES6中可以给参数指定默认值,确实带来很多便利. 如果需要检测某些参数是必传时,可以这么做

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// 这里将抛出一个错误,因为名字时必须
hello();
// 这也将抛出一个错误
hello(undefined);

// 正常
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;

获取查询参数
多年来,我们编写粗糙的正则表达式来获取查询字符串值,但那些日子已经一去不复返了; 现在我们可以通过 URLSearchParams API 来获取查询参数

在不使用 URLSearchParams 我们通过正则的方式来完成获取查询参数的, 如下:

function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + “=([^&]*)(&|$)”);
var r = window.location.search.substr(1).match(reg);
return r ? r[2] : null;
}
使用 URLSearchParams 之后:

// 假设地址栏中查询参数是这样 "?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"

相比之前使用起来更加容易了.

原文:https://blog.csdn.net/qq_43258252/article/details/94737380

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值