作者:jenemy
https://segmentfault.com/a/1190000011557368
本文內(nèi)容來自知乎《有哪些短小卻令人驚嘆的 JavaScript 代碼?》和文章《這些JavaScript編程黑科技,裝逼指南,高逼格代碼,讓你驚嘆不已》,同時(shí)也匯集了部分網(wǎng)上其它來源的內(nèi)容。
浮點(diǎn)數(shù)取整
const x = 123.4545;
x >> 0; // 123
~~x; // 123
x | 0; // 123
Math.floor(x); // 123
注意:前三種方法只適用于32個(gè)位整數(shù),對(duì)于負(fù)數(shù)的處理上和
Math.floor是不同的。
Math.floor(-12.53); // -13
-12.53 | 0; // -12
生成6位數(shù)字驗(yàn)證碼
// 方法一
('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進(jìn)制顏色代碼生成
(function() {
?return '#'+('00000'+
? ?(Math.random()*0x1000000<<0).toString(16)).slice(-6);
})();
駝峰命名轉(zhuǎn)下劃線
'componentMapModelRegistry'.match(/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g).join('_').toLowerCase(); // component_map_model_registry
url查詢參數(shù)轉(zhuǎn)json格式
// ES6
const query = (search = '') => ((querystring = '') => (q => (querystring.split('&').forEach(item => (kv => kv[0] && (q[kv[0]] = kv[1]))(item.split('='))), q))({}))(search.split('?')[1]);
// 對(duì)應(yīng)ES5實(shí)現(xiàn)
var query = function(search) {
?if (search === void 0) { search = ''; }
?return (function(querystring) {
? ?if (querystring === void 0) { querystring = ''; }
? ?return (function(q) {
? ? ?return (querystring.split('&').forEach(function(item) {
? ? ? ?return (function(kv) {
? ? ? ? ?return kv[0] && (q[kv[0]] = kv[1]);
? ? ? ?})(item.split('='));
? ? ?}), q);
? ?})({});
?})(search.split('?')[1]);
};
query('?key1=value1&key2=value2'); // es6.html:14 {key1: "value1", key2: "value2"}
獲取URL參數(shù)
function getQueryString(key){
?var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
?var r = window.location.search.substr(1).match(reg);
?if(r!=null){
? ? ?return ?unescape(r[2]);
?}
?return null;
}
n維數(shù)組展開成一維數(shù)組
var foo = [1, [2, 3], ['4', 5, ['6',7,[8]]], [9], 10];
// 方法一
// 限制:數(shù)組項(xiàng)不能出現(xiàn)`,`,同時(shí)數(shù)組項(xiàng)全部變成了字符數(shù)字
foo.toString().split(','); // ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
// 方法二
// 轉(zhuǎn)換后數(shù)組項(xiàng)全部變成數(shù)字了
eval('[' + foo + ']'); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 方法三,使用ES6展開操作符
// 寫法太過麻煩,太過死板
[1, ...[2, 3], ...['4', 5, ...['6',7,...[8]]], ...[9], 10]; // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]
// 方法四
JSON.parse(`[${JSON.stringify(foo).replace(/[|]/g, '')}]`); // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]
// 方法五
const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
flatten(foo); // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]
// 方法六
function flatten(a) {
?return Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
}
flatten(foo); // [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]
注:更多方法請(qǐng)參考《How to flatten nested array in JavaScript?》
日期格式化
// 方法一
function format1(x, y) {
?var z = {
? ?y: x.getFullYear(),
? ?M: x.getMonth() + 1,
? ?d: x.getDate(),
? ?h: x.getHours(),
? ?m: x.getMinutes(),
? ?s: x.getSeconds()
?};
?return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) {
? ?return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
?});
}
format1(new Date(), 'yy-M-d h:m:s'); // 17-10-14 22:14:41
// 方法二
Date.prototype.format = function (fmt) {
?var o = {
? ?"M+": this.getMonth() + 1, //月份
? ?"d+": this.getDate(), //日
? ?"h+": this.getHours(), //小時(shí)
? ?"m+": this.getMinutes(), //分
? ?"s+": this.getSeconds(), //秒
? ?"q+": 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.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
? ?}
?} ? ?
?return fmt;
}
new Date().format('yy-M-d h:m:s'); // 17-10-14 22:18:17
統(tǒng)計(jì)文字個(gè)數(shù)
function wordCount(data) {
?var pattern = /[a-zA-Z0-9_Β-ω]+|[一-??-?豈-??-??-?]+/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 = '貸款買房,也意味著你能給自己的資產(chǎn)加杠桿,能夠撬動(dòng)更多的錢,來孳生更多的財(cái)務(wù)性收入。';
wordCount(text); // 38
特殊字符轉(zhuǎn)義
function htmlspecialchars (str) {
?var str = str.toString().replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"');
?return str;
}
htmlspecialchars('&jfkds<>'); // "&jfkds<>"
動(dòng)態(tài)插入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);
}
格式化數(shù)量
// 方法一
function formatNum (num, n) {
?if (typeof num == "number") {
? ?num = String(num.toFixed(n || 0));
? ?var re = /(-?d+)(d{3})/;
? ?while (re.test(num)) num = num.replace(re, "$1,$2");
? ?return num;
?}
?return num;
}
formatNum(2313123, 3); // "2,313,123.000"
// 方法二
'2313123'.replace(/B(?=(d{3})+(?!d))/g, ','); // "2,313,123"
// 方法三
function formatNum(str) {
?return str.split('').reverse().reduce((prev, next, index) => {
? ?return ((index % 3) ? next : (next + ',')) + prev
?});
}
formatNum('2313323'); // "2,313,323"
身份證驗(yàn)證
function chechCHNCardId(sNo) {
?if (!this.regExpTest(sNo, /^[0-9]{17}[X0-9]$/)) {
? ?return false;
?}
?sNo = sNo.toString();
?var a, b, c;
?a = parseInt(sNo.substr(0, 1)) * 7 + parseInt(sNo.substr(1, 1)) * 9 + parseInt(sNo.substr(2, 1)) * 10;
?a = a + parseInt(sNo.substr(3, 1)) * 5 + parseInt(sNo.substr(4, 1)) * 8 + parseInt(sNo.substr(5, 1)) * 4;
?a = a + parseInt(sNo.substr(6, 1)) * 2 + parseInt(sNo.substr(7, 1)) * 1 + parseInt(sNo.substr(8, 1)) * 6;
?a = a + parseInt(sNo.substr(9, 1)) * 3 + parseInt(sNo.substr(10, 1)) * 7 + parseInt(sNo.substr(11, 1)) * 9;
?a = a + parseInt(sNo.substr(12, 1)) * 10 + parseInt(sNo.substr(13, 1)) * 5 + parseInt(sNo.substr(14, 1)) * 8;
?a = a + parseInt(sNo.substr(15, 1)) * 4 + parseInt(sNo.substr(16, 1)) * 2;
?b = a % 11;
?if (b == 2) {
? ?c = sNo.substr(17, 1).toUpperCase();
?} else {
? ?c = parseInt(sNo.substr(17, 1));
?}
?switch (b) {
? ?case 0:
? ? ?if (c != 1) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 1:
? ? ?if (c != 0) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 2:
? ? ?if (c != "X") {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 3:
? ? ?if (c != 9) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 4:
? ? ?if (c != 8) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 5:
? ? ?if (c != 7) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 6:
? ? ?if (c != 6) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 7:
? ? ?if (c != 5) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 8:
? ? ?if (c != 4) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 9:
? ? ?if (c != 3) {
? ? ? ?return false;
? ? ?}
? ? ?break;
? ?case 10:
? ? ?if (c != 2) {
? ? ? ?return false;
? ? ?};
?}
?return true;
}
測(cè)試質(zhì)數(shù)
function isPrime(n) {
?return !(/^.?$|^(..+?)+$/).test('1'.repeat(n))
}
統(tǒng)計(jì)字符串中相同字符出現(xiàn)的次數(shù)
var arr = 'abcdaabc';
var info = arr
? ?.split('')
? ?.reduce((p, k) => (p[k]++ || (p[k] = 1), p), {});
console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }
使用?void0來解決?undefined被污染問題
undefined = 1;
!!undefined; // true
!!void(0); // false
單行寫一個(gè)評(píng)級(jí)組件
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
JavaScript 錯(cuò)誤處理的方式的正確姿勢(shì)
try {
? ?something
} catch (e) {
? ?window.location.href =
? ? ? ?"http://stackoverflow.com/search?q=[js]+" +
? ? ? ?e.message;
}
匿名函數(shù)自執(zhí)行寫法
( function() {}() );
( function() {} )();
[ function() {}() ];
~ function() {}();
! function() {}();
+ function() {}();
- function() {}();
delete function() {}();
typeof function() {}();
void function() {}();
new function() {}();
new function() {};
var f = function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();
兩個(gè)整數(shù)交換數(shù)值
var a = 20, b = 30;
a ^= b;
b ^= a;
a ^= b;
a; // 30
b; // 20
數(shù)字字符轉(zhuǎn)數(shù)字
var a = '1';
+a; // 1
最短的代碼實(shí)現(xiàn)數(shù)組去重
[...new Set([1, "1", 2, 1, 1, 3])]; // [1, "1", 2, 3]
用最短的代碼實(shí)現(xiàn)一個(gè)長(zhǎng)度為m(6)且值都n(8)的數(shù)組
Array(6).fill(8); // [8, 8, 8, 8, 8, 8]
將argruments對(duì)象轉(zhuǎn)換成數(shù)組
var argArray = Array.prototype.slice.call(arguments);
// ES6:
var argArray = Array.from(arguments)
// or
var argArray = [...arguments];
獲取日期時(shí)間綴
// 獲取指定時(shí)間的時(shí)間綴
new Date().getTime();
(new Date()).getTime();
(new Date).getTime();
// 獲取當(dāng)前的時(shí)間綴
Date.now();
// 日期顯示轉(zhuǎn)換為數(shù)字
+new Date();
使用?~x.indexOf('y')來簡(jiǎn)化?x.indexOf('y')>-1
var str = 'hello world';
if (str.indexOf('lo') > -1) {
?// ...
}
if (~str.indexOf('lo')) {
?// ...
}
parseInt()?or?Number()
兩者的差別之處在于解析和轉(zhuǎn)換兩者之間的理解。
解析允許字符串中含有非數(shù)字字符,解析按從左到右的順序,如果遇到非數(shù)字字符就停止。而轉(zhuǎn)換不允許出現(xiàn)非數(shù)字字符,否者會(huì)失敗并返回NaN。
var a = '520';
var b = '520px';
Number(a); // 520
parseInt(a); // 520
Number(b); // NaN
parseInt(b); // 520
parseInt方法第二個(gè)參數(shù)用于指定轉(zhuǎn)換的基數(shù),ES5默認(rèn)為10進(jìn)制。
parseInt('10', 2); // 2
parseInt('10', 8); // 8
parseInt('10', 10); // 10
parseInt('10', 16); ?// 16
對(duì)于網(wǎng)上 parseInt(0.0000008)的結(jié)果為什么為8,原因在于0.0000008轉(zhuǎn)換成字符為"8e-7",然后根據(jù) parseInt的解析規(guī)則自然得到"8"這個(gè)結(jié)果。
+ 拼接操作,+x or String(x)?
+運(yùn)算符可用于數(shù)字加法,同時(shí)也可以用于字符串拼接。如果+的其中一個(gè)操作符是字符串(或者通過 隱式強(qiáng)制轉(zhuǎn)換可以得到字符串),則執(zhí)行字符串拼接;否者執(zhí)行數(shù)字加法。
需要注意的時(shí)對(duì)于數(shù)組而言,不能通過 valueOf()方法得到簡(jiǎn)單基本類型值,于是轉(zhuǎn)而調(diào)用 toString()方法。
[1,2] + [3, 4]; // "1,23,4"
對(duì)于對(duì)象同樣會(huì)先調(diào)用 valueOf()方法,然后通過 toString()方法返回對(duì)象的字符串表示。
var a = {};
a + 123; // "[object Object]123"
對(duì)于 a+""隱式轉(zhuǎn)換和 String(a)顯示轉(zhuǎn)換有一個(gè)細(xì)微的差別: a+''會(huì)對(duì)a調(diào)用 valueOf()方法,而 String()直接調(diào)用 toString()方法。大多數(shù)情況下我們不會(huì)考慮這個(gè)問題,除非真遇到。
var a ?= {
?valueOf: function() { return 42; },
?toString: function() { return 4; }
}
a + ''; // 42
String(a); // 4
判斷對(duì)象的實(shí)例
// 方法一: ES3
function Person(name, age) {
?if (!(this instanceof Person)) {
? ?return new Person(name, age);
?}
?this.name = name;
?this.age = age;
}
// 方法二: ES5
function Person(name, age) {
?var self = this instanceof Person ? this : Object.create(Person.prototype);
?self.name = name;
?self.age = age;
?return self;
}
// 方法三:ES6
function Person(name, age) {
?if (!new.target) {
? ?throw 'Peron must called with new';
?}
?this.name = name;
?this.age = age;
}
數(shù)據(jù)安全類型檢查
// 對(duì)象
function isObject(value) {
?return Object.prototype.toString.call(value).slice(8, -1) === 'Object'';
}
// 數(shù)組
function isArray(value) {
?return Object.prototype.toString.call(value).slice(8, -1) === 'Array';
}
// 函數(shù)
function isFunction(value) {
?return Object.prototype.toString.call(value).slice(8, -1) === 'Function';
}
讓數(shù)字的字面值看起來像對(duì)象
2.toString(); // Uncaught SyntaxError: Invalid or unexpected token
2..toString(); // 第二個(gè)點(diǎn)號(hào)可以正常解析
2 .toString(); // 注意點(diǎn)號(hào)前面的空格
(2).toString(); // 2先被計(jì)算
對(duì)象可計(jì)算屬性名(僅在ES6中)
var suffix = ' name';
var person = {
?['first' + suffix]: 'Nicholas',
?['last' + suffix]: 'Zakas'
}
person['first name']; // "Nicholas"
person['last name']; // "Zakas"