JavaScript 有用的代码片段

-----一、浮点数取整

//前三种方法只适用于32个位整数,对于负数的处理上和 Math.floor是不同的。
const x = 123.4545;
x >> 0; // 123
~~x; // 123
x | 0; // 123
Math.floor(x); // 123

-----二、生成6位数字验证码

// 方法1
('000000' + Math.floor(Math.random() * 999999)).slice(-6);
// 方法2
Math.random().toString().slice(-6);
// 方法3
Math.random().toFixed(6).slice(-6);
// 方法4
'' + Math.floor(Math.random() * 999999);

-----三、16进制颜色代码生成

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

-----四、驼峰命名转下划线

'componentMapModelRegistry'.match(/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g).join('_').toLowerCase(); // component_map_model_registry

-----五、url查询参数转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]);

-----六、对应ES5实现

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]);
};

// es6.html:14 {key1: "value1", key2: "value2"}
query('?key1=value1&key2=value2');

-----七、获取URL参数

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维数组展开成一维数组

var foo = [1, [2, 3],
    ['4', 5, ['6', 7, [8]]],
    [9], 10
];

// 方法1
// 限制:数组项不能出现`,`,同时数组项全部变成了字符数字
foo.toString().split(',');
// ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

// 方法2
// 转换后数组项全部变成数字了
eval('[' + foo + ']');
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// 方法3,使用ES6展开操作符
// 写法太过麻烦,太过死板
[1, ...[2, 3], ...['4', 5, ...['6', 7, ...[8]]], ...[9], 10];
// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]

// 方法4
JSON.parse(`[${JSON.stringify(foo).replace(/\[|]/g,'')}]`);
// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]

// 方法5
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]

// 方法6
function flatten(a) { return Array.isArray(a) ? [].concat(...a.map(flatten)) : a; }
flatten(foo);
// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]

-----九、 日期格式化

//方法1

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

//方法2
Date.prototype.format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份     "d+": this.getDate(), //日     "h+": this.getHours(), //小时
        "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

-----十、 统计文字个数

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); // 38

-----十一、特殊字符转义

function htmlspecialchars(str) {
    var str = str.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, '&quot;');
    return str;
}
htmlspecialchars('&jfkds<>'); // "&amp;jfkds&lt;&gt;"

-----十二、动态插入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);
}

-----十三、格式化数量

// 方法1
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"
// 方法2
'2313123'.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // "2,313,123"
// 方法3
function formatNum(str) {
    return str.split('').reverse().reduce((prev, next, index) => {
        return ((index % 3) ? next : (next + ',')) + prev;
    });
}
formatNum('2313323'); // "2,313,323"

----- 测试质数

function isPrime(n) {
  return !(/^.?$|^(..+?)\1+$/).test('1'.repeat(n));
}

----- 统计字符串中相同字符出现的次数

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 }

----- 单行写一个评级组件

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

----- 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() {}();
void function() {}();
new function() {}();
new function() {};


var f = function() {}();

1, function() {}();
1 ^ function() {}();
1 > function() {}();

----- 两个整数交换数值

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

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);
// [8, 8, 8, 8, 8, 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();  // 日期显示转换为数字


#### ----- 使用 ~x.indexOf('y')来简化 x.indexOf('y')>-1
var str = 'hello world';
if (str.indexOf('lo') > -1) {
    // ...
}
if (~str.indexOf('lo')) {
    // ...
}

----- 数据安全类型检查

// 对象
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';
}

参考:https://mp.weixin.qq.com/s?__biz=MjM5MDA2MTI1MA==&mid=2649087655&idx=2&sn=b6c1057e1fd18a91fb491ff0a3bcc6ec&chksm=be5bf90a892c701c1d8b746d747e583840cd2a563f1c88e3cb686aced49798fb707904cbdb1a

posted @ 2018-04-25 20:27  oneVillager  阅读(119)  评论(0编辑  收藏  举报
打赏

喜欢请打赏

扫描二维码打赏