JS操作小技巧

1.数组去重

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
//Result: [1, 2, 3, 5]

2.浮点数转整数

console.log(10.9 | 0);  // 10
console.log(-10.9 | 0); // -10
console.log(23.9 | 0); // Result: 23
console.log(-23.9 | 0); // Result: -23

3.数组降维度

let arr = [ [1], [2], [3] ];
arr = Array.prototype.concat.apply([], arr);
console.log(arr);// [1, 2, 3]

let array = [ [1], [2], [3] ];
array = array.flat(2);
console.log(array); // [1, 2, 3]

let arrMore = [1, 2, [3], [[4]]];
arrMore = arrMore.flat(Infinity);
console.log(arrMore);[1, 2, 3, 4]

4.短路求值

x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';

但有时候三元运算符仍然很复杂,我们可以使用逻辑运算符 && 和||来替代,让代码更简洁一些。这种技巧通常被称为“短路求值”。

假设我们想要返回两个或多个选项中的一个,使用 && 可以返回第一个 false。如果所有操作数的值都是 true,将返回最后一个表达式的值

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3
console.log(0 && null); // Result: 0

使用||可以返回第一个 true。如果所有操作数的值都是 false,将返回最后一个表达式的值。

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1
console.log(0 || null); // Result: null

5.幂运算

//比Math.power(2,3)
console.log(2 ** 3); // Result: 8
console.log(2 ** 4); // Result: 16

6.转数字

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

console.log(+true); // Return: 1
console.log(+false); // Return: 0

7.统计字符串中出现次数最多的字符

//统计每个字母出现的次数,然后存起来,然后进行比较
function maxTimesChar(str) {  
  if(str.length == 1) {
    return str;
  }
  let charObj = {};
  for(let i=0;i<str.length;i++) {
    if(!charObj[str.charAt(i)]) {
      charObj[str.charAt(i)] = 1;
    }else{
      charObj[str.charAt(i)] += 1;
    }
  }
  let maxChar = '',
      maxValue = 1;
  for(var k in charObj) {
    if(charObj[k] >= maxValue) {
      maxChar = k;
      maxValue = charObj[k];
    }
  }
  return maxChar;

}

8.数组合并

var a = [1,2,3];
var b=[4,5]
a = a.concat(b);
console.log(a);
//此处输出为 [1, 2, 3 ,4 ,5]

// ES5 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1)//[0,1,2,3,4,5]

// ES6 的写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1)//[0,1,2,3,4,5]

9.slice截取

var str1 = 'nihaoya wobuhaoya'
console.log(str1.slice(4,9)); //4位置开始,到9的前一个位置结束
console.log(str1.slice(2,14));//start位置开始,end前一个位置结束
console.log(str1);//原字符串不变
console.log(str1.slice(-1,0)); //返回的是空字符串
console.log(str1.slice(30,100)); //长度超过字符串的长度,返回空字符串
console.log(str1.slice(-1,10));//返回的是空字符串
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lbchenxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值