JavaScript奇技淫巧

  • 单行写一个评级系统
var rate = 3;
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
    
  • CSS调试黑科技,所有元素加 随机色的outline
[].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)}`)

  • 随机字符串
Math.random().toString(16).substring(2)

  • 实现金钱格式化

//正则表达式实现:
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

  • Json的深拷贝
var a = {
    a: 1,
    b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))
console.log( a === b , a.b === b.b ) //false , false

  • 数组去重

var arr = [1, "1", 2, 1, 1, 3];
var newArr = [...new Set(arr)]; // [1,'1',2,3]

// 注意:语法都为ES6的语法,所以存在兼容问题

  • 类数组对象转换成数组

// arguments为类数组
var argArray = Array.prototype.slice.call(arguments);

// 或者ES6:
var argArray = Array.from(arguments)

原文地址:https://www.cnblogs.com/koala0521/p/7889146.html