JavaScript 有用的代碼片斷和 trick

本文取自於Jenemyjavascript

https://segmentfault.com/a/1190000011557368java

浮點數取整segmentfault

const x = 123.456;數組

x >> 0;//123安全

x | 0;//123dom

~~x;//123async

Math.floor(x);//123函數

對於負數的處理不同測試

Math.floor(-12.53);//-13this

-12.53 | 0;//-12

生成6位數字驗證碼

//方法一
('000000' + Math.floor(Math.random() * 999999)).slice(-6);

//方法二
Math.random().toString().slice(-6);

//方法三
Math.random().toFixed(6).slice(-6);
//方法四
'' + Math.floor(Math.random() * 999999);

16進制顏色代碼生成

(function(){
return '#' + ('0000'+
(Math.random()*0x1000000<<0).toString(16)).slice(-6);
})();

駝峯命名轉下劃線

'componentMapMod.mat/^[a-z][a-z0-9]+|[A g).j').toLowerC
elRegistry' ch( -Z][a-z0-9])*/

n維數組展開成一維數組

 

//方法一
var foo = [1,[2,3],['4',5,['6',7,[8]]],[9],10];
foo.toString().split(',');

 

//方法二
eval('[' + foo +']');


//方法三
function flatten(a){
return Arrary.isArray(a)?[].concat(...a.map(flatten)):a;
}
flatten(foo);

注:更多方法請參考《How to flatten nested array in JavaScript?》

日期格式化

//方法一

function format1(x,y){
var z = {
y: x.getFullYear(),
M: x.getMonth(),
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
return y.repalce(/(y+|M+|d+|h+|m+|s+)/g, function(v){
return ((h>v.length 1?"0":"")+eval('z'+v.slice(-1))).slice(-(v.length2?:v.length2))
});
}
format1(new Date(),'yy-M-d h:m:s');

//方法二

Date.prototype.format = function(fmt){
var o = {
"M+": this.getMonth()+1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": this.Math.floor((this.getMonth() + 3) / 3),//季度
"S+": this.getMilliseconds(),//毫秒
};
if(/(y+)/.test(fmt)){
fmt = fmt.replace(RegExp.$1, this.getFullYear()+"").substr(4 - RegExp.$1.length)
}
for (var k in o){
if(new RegExp("(" + k + ")").test(fmt)){
fmt = fmt.RegExp.$1.length == 1?(o[k]"0" : o[k].substr(o[k].length))
}
}
return fmt;
}
new Date().format('yy-N-d h:m:s');

統計文字個數

function wordCount(data){
var pattern = /[a-zA-Z0-9_\u0392-\u03c9] +| [\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;

var m = data.match(pattern);
var count = 0;
if(m===null) return count;
for(var i=0;i<m.length;i++){
if(m[i].charCodeAt(0) >= 0x4E00) {
count += m[i].length;
}else{
count += 1;
}
}
return count;
}
var text = '貸款買房,也意味着你能給本身的資產加槓桿,可以撬動更多的錢,來孳生更多的財務性收入.';
wordCount(text);

動態插入js

function injectScript(src){
var s,t;
s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = src;
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s.t);
}

測試質數

function isPrime(n){

統計字符串中相同字符出現的次數

var arr = 'abcdaabc';
var info = arr
.split('')
.reduce((p,k) => (p[k]++ || (p[k] = 1),p),{});
console.log(info);

單行寫一個評級組件

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

使用 void0來解決 undefined被污染問題

undefined = 1;
!!undefined; //true
!!void(0); //false

JavaScript 錯誤處理的方式的正確姿式

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

匿名函數自執行寫法

( function() {}() );
( function() {} )();
[ function() {}() ];
~ function() {}();
! function() {}();
+ function() {}();
- function() {}();
delete function() {}();
typeof function() {}();
voidfunction() {}();
newfunction() {}();
newfunction() {};
var f = function() {}();
1, function() {}();
1^ function() {}();
1> function() {}();

兩個整數交換數值

var a = 20, b = 30;
a ^= b;
b ^= a;
a; //30
b; //20

數字字符轉數字

var a = '1';

+a; //1

最短的代碼實現數組去重

[...new Set([1,"1",2,1,1,3])];//(1,"1",2,3)

用最短的代碼實現一個長度爲m(6)且值都n(8)的數

Array(6).fill(8);

將argruments對象轉換成數組

var argArray = Array.prototype.slice.call(arguments);
//ES6:
var argArray = Array.from(arguments);
//or
var argArray = [...arguments];

獲取日期時間綴

// 獲取指定時間的時間綴
new Date().getTime();
(new Date()).getTime();
(new Date).getTime();

Date.now();// 獲取當前的時間綴

+new Date();// 日期顯示轉換爲數字

數據安全類型檢查

// 對象

function isObject(value) {
return Object.prototype.toString.call(value).slice(8, -1) === 'Object';
}
// 數組
function isArray(value) {
return Object.prototype.toString.call(value).slice(8, -1) === 'Array';
}
// 函數
function isFunction(value) {
return Object.prototype.toString.call(value).slice(8, -1) === 'Function';
}

讓數字的字面值看起來像對象

2.toString(); // Uncaught SyntaxError: Invalid or unexpected token
2..toString(); // 第二個點號能夠正常解析
2. toString(); // 注意點號前面的空格
(2).toString(); // 2先被計算

對象可計算屬性名(僅在ES6中)

var suffix = ' name';var person = { ['first' + suffix]: 'Nicholas', ['last'+ suffix]: 'Zakas'}person['first name']; // "Nicholas"person['last name']; // "Zakas"

相關文章
相關標籤/搜索