前端有用JavaScript技巧

数组去重

 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]

合并对象

const page = {
 current: 1,
 pageSize: 10
 }
 const form = {
 name: "",
 sex: ""
 }
 const params = {...form, ...page};
 /*
 {
 name: "",
 sex: "",
 current: 1,
 pageSize: 10
 }
 *

获取查询参数

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

||与&&用法

a() && b() :如果执行a()后返回true,则执行b()并返回b的值;如果执行a()后返回false,则整个表达式返回a()的值,b()不执行;

a() || b() :如果执行a()后返回true,则整个表达式返回a()的值,b()不执行;如果执行a()后返回false,则执行b()并返回b()的值;

    console.log(0 && 4); //0
    console.log(1 && 4); //4
    console.log(0 || 4); //4
    console.log(1 || 4); //1
    console.log((1 && 3 || 0) && 4); //4 
    console.log(1 && 3 || 0 && 4); //3 
    console.log(0 && 3 || 1 && 4); //4 

 

转载于:https://www.cnblogs.com/lwming/p/11154589.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值