Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js逼格代码 #2

Open
flyingliu opened this issue Sep 1, 2017 · 0 comments
Open

js逼格代码 #2

flyingliu opened this issue Sep 1, 2017 · 0 comments

Comments

@flyingliu
Copy link
Owner

1、单行写一个评级组件

var rate = 3
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

定义一个变量rate是1到5的值,然后执行上面代码

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

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

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

[].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) // 13位
Math.random().toString(36).substring(2) // 11位

(10)["toString"](36) === "a" 
(35)["toString"](36) === "z"

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

用正则魔法实现:

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

6、实现标准JSON的深拷贝

var a = {
    a: 1,
    b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))

不考虑IE的情况下,标准JSON格式的对象蛮实用,不过对于undefined和function的会忽略掉。

7、javascript高逼格之Function构造函数

很多JavaScript教程都告诉我们,不要直接用内置对象的构造函数来创建基本变量,例如var arr = new Array(2); 的写法就应该用var arr = [1, 2];的写法来取代。

但是,Function构造函数(注意是大写的Function)有点特别。Function构造函数接受的参数中,第一个是要传入的参数名,第二个是函数内的代码(用字符串来表示)。

var f = new Function('a,b', 'console.log(a,b)');
f('jawil',1); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant