1. Usage of Unicode Character
“I hear and I forget. I see and I remember. I do and I understand.”
1 2
| var rate = 3 "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
|
2. An efficient way to handle JavaScript exception
1 2 3 4 5 6 7 8
| try { } catch (e) { window.location.href = "http://stackoverflow.com/search?q=[js]+" + e.message; }
|
3. Locate all DOM elements visually
1 2 3 4 5 6 7 8
| [].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. Separate number with ,
1 2 3 4
| var test1 = '1234567890' var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',') console.log(format)
|
5. An unofficial way to do deep clone for JSON object
1 2 3 4 5
| var a = { a: 1, b: { c: 1, d: 2 } } var b=JSON.parse(JSON.stringify(a))
|
6. Implicitly convert string to number
7. Usage of ES6 Spread Operator
1 2 3 4 5
| [...new Set([2, "2", 3, 3, 4, 1])] Array(3).fill(2)
|
8. Find Max and Min use Math
1 2 3
| var numbers = [-99, 0 , 99 , 98 , -1]; var maxNum = Math.max.apply(Math, numbers); var minNum = Math.min.apply(Math, numbers);
|
9. Debugging tips
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var fruits = [ { fruit: 'Tangerine', weight: 43 }, { fruit: 'Cherry', weight: 13 }, { fruit: 'Litchi', weight: 25 } ]; console.table(fruits); console.time('Timer01'); var items = []; for(var i = 0; i < 100000; i++){ items.push({index: i}); } console.timeEnd('Timer01');
|
10. Remove Timers from Global Scope
1 2 3 4
| var highestTimeoutId = setTimeout(";"); for(var i=0; i<hightestTimeoutId; i++){ clearTimeout(i); }
|