码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript奇技淫巧

时间:2017-11-24 14:58:30      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:log   replace   reac   兼容问题   $$   去重   ice   return   out   

  • 单行写一个评级系统
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)

JavaScript奇技淫巧

标签:log   replace   reac   兼容问题   $$   去重   ice   return   out   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!