JavaScript 有用的代码片段和 trick

本文取自于Jenemy

https://segmentfault.com/a/1190000011557368

浮点数取整

const x = 123.456;

x >> 0;//123

x | 0;//123

~~x;//123

Math.floor(x);//123

对于负数的处理不一样

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

-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"

posted @ 2018-08-21 16:14  Sueing  阅读(169)  评论(0编辑  收藏  举报
[URL=https://info.flagcounter.com/X5yY][IMG]https://s05.flagcounter.com/map/X5yY/size_s/txt_000000/border_CCCCCC/pageviews_0/viewers_0/flags_0/[/IMG][/URL]