JavaScript 编程黑科技,一些小技巧(一)

1、论如何优雅的取随机字符串(.substring() 的第二个参数控制取多少位 (最多可取13位))

Math.random().toString(16).substring(2) // 13位
Math.random().toString(36).substring(2) // 11位

 

 

2、论如何优雅的取整

var a = ~~2.33
var b= 2.33 | 0
var c= 2.33 >> 0

 

 

 3、如何优雅的实现金钱格式化:1234567890 --> 1,234,567,890;

用toLocaleString()实现

用正则魔法实现:

var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) // 1,234,567,890

非正则的优雅实现:

function formatCash(str) {
       return str.split('').reverse().reduce((prev, next, index) => {
            return ((index % 3) ? next : (next + ',')) + prev
       })
}
console.log(formatCash('1234567890')) // 1,234,567,890

4、论如何最佳的让两个整数交换数值

var a=1,b=2;
a += b;
b = a - b;
a -= b;

缺点也很明显,整型数据溢出,对于32位字符最大表示数字是2147483647,如果是2147483645和2147483646交换就失败了。黑科技办法:

a ^= b;
b ^= a;
a ^= b;

 3.1 使用&运算符判断一个数的奇偶

// 偶数 & 1 = 0
// 奇数 & 1 = 1
console.log(2 & 1)    // 0
console.log(3 & 1)    // 1

3.2  使用~, >>, <<, >>>, |来取整

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

 

 

 看不懂的童鞋建议去补习一下C语言的位操作。

5、最短的代码实现数组去重

[...new Set([1, "1", 2, 1, 1, 3])]

 6、取出一个数组中的最大值和最小值

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; 
var maxInNumbers = Math.max.apply(Math, numbers); 
var minInNumbers = Math.min.apply(Math, numbers);

7、一行代码完成时间戳转换

// 传入时间戳
function time(t) {
  var date = new Date(t);
  return date.toJSON().substr(0,19).replace('T', ' ') // 2018-09-02 18:34:35
  // return date.toJSON().substr(0,19).replace('T', ' ').replace(/-/g, '.') // 2018.09.02 18:34:35
}
time(t) 

Date的‘toJSON’方法返回格林威治时间的JSON格式字符串,实际是使用‘toISOString’方法的结果。字符串形如‘2018-08-09T10:20:54.396Z’,转化为北京时间需要额外增加八个时区,我们需要取字符串前19位,然后把‘T’替换为空格,即是我们需要的时间格式。

8、计算数组中每个元素出现的次数

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

9、if语法简化

假如我们有下面的代码:

if(value === 'duck' || value === 'dog' || value === 'cat') {
  // ...
}

我们可以这样写:

const options = ['duck', 'dog', 'cat'];
if (options.includes(value)) {
  // ...
}

 10、求2个数组的交集

const firstArray = [2, 2, 4, 1];
const secondArray = [1, 2, 0, 5];

function intersection(firstArray, secondArray) {
  const hashmap = {};
  const intersectionArray = [];

  firstArray.forEach(element => {
    console.log(element)
    hashmap[element] = 1;
  });
  console.log(hashmap)

  secondArray.forEach(element => {
    console.log(hashmap[element])
    if (hashmap[element] === 1) {
      intersectionArray.push(element);
      hashmap[element]++;

    }
  });

  return intersectionArray;
}
intersection(firstArray, secondArray); // [2, 1]

 

posted @ 2020-11-16 15:25  府谷市民小柴  阅读(76)  评论(0编辑  收藏  举报