js缩减代码

1.获取url参数
let q={};
location.search.replace(/([?&=]+)=([&]+)/g,(_,k,v)=>q[k]=v);
console.log(q)

2.随机生成十六进制颜色
console.log(’#’ + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, ‘0’))

3.数组去重
let arr = [1,2,3,1,2,3,4,]
console.log([…new Set(arr)])

4.数组转为对象
const arr = [1,2,3]
const obj = {…arr}
console.log(obj)

4.三元表达
const isGood = true;
const feeling = isGood ? ‘good’ : ‘bad’
console.log(I feel ${feeling})

5.合并对象
const obj1 = { a: 1 }
const obj2 = { b: 2 }
const combinObj = { …obj1, …obj2 }
console.log(combinObj)

6.递归
let arr = [1, [2, 3, [4, [5]]]];
arr.flat(3); // [1,2,3,4,5]

7.幂次方和取整
console.log(2 ** 10); // 输出1024

console.log(~~6.95); // 6
console.log(6.95 >> 0); // 6
console.log(6.95 << 0); // 6
console.log(6.95 | 0); // 6
// >>>不可对负数取整
console.log(6.95 >>> 0); // 6

8.获取数组最后一个元素
let arr = [0, 1, 2, 3, 4, 5];
const last = arr[arr.length - 1];
console.log(last);

9.复制数组
const arr = [1, 2, 3, 4, 5];
const copyArr = arr.concat();

10.替代if判断
switch(status) {
case ‘process’:console.log(‘哈哈’)
case ‘wait’:
case ‘fail’:
this.doSomething()
}
11.判断是否以某个元素结束
String.prototype.endWith = function(s) {
var d = this.length - s.length;
return d >= 0 && this.lastIndexOf(s) == d;
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值