ahalf-yuan / blog

一些学习记录,整理中...
0 stars 0 forks source link

短小精湛的代码 #7

Open ahalf-yuan opened 5 years ago

ahalf-yuan commented 5 years ago

这些JavaScript编程黑科技,装逼指南,高逼格代码,让你惊叹不已

1.Tiny Rate

包含小数的实现 ★构建东半球最小的评级组件☆

function rate(num){
  return "★★★★★☆☆☆☆☆".slice(5 - num, 10 - num);
}
rate(3)   // "★★★☆☆"

2.JavaScript 错误处理的方式的正确姿势

跳转到 stackoverflow 网站。

try {
    something
} catch (e) {
    window.location.href =
        "http://stackoverflow.com/search?q=[js]+" +
        e.message;
}

3.从一行代码里面学点JavaScript

将页面所有的元素用不同颜色的1px 的边框包裹。

[从一行代码里面学点 JavaScript]

[Learning much javascript from one line of code]

[].forEach.call($$("*"),function(a){
    a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})

翻译成正常语言

Array.prototype.forEach.call(document.querySelectorAll('*'), 
dom => dom.style.outline = `1px solid #${parseInt(Math.random() * 
Math.pow(2,24)).toString(16)}`)

4.论如何优雅的取随机字符串

Math.random().toString(16).substring(2) 
Math.random().toString(36).substring(2)

5.论如何优雅的取整

var a = ~~2.33

var b= 2.33 | 0

var c= 2.33 >> 0

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

var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')

console.log(format) // 1,234,567,890

7.用最短的代码实现一个长度为m(6)且值都n(8)的数组

Array(6).fill(8)

8.取出一个数组中的最大值和最小值

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

金钱格式化:1234567890 --> 1,234,567,890; 中的正则/\B(?=(\d{3})+(?!\d))/g

解释:

可以理解为?=是一个狂妄的预言家,假设有正则 /abc?=xxx/,它预言自己出现的位置后面一定、肯定、必须、只能是 xxx,如果不是,那它会以死明志的(就是匹配失败)。
所以,?=(\d{3})+(?!\d)匹配三个数字的一组或多组数字 且 不能以数字结尾 的位置。

image

问题:什么是零宽断言???

正则分析网站

Regulex regexper