1、数组去重
去除数组中重复的元素。
function unique(arr) { var res = []; var json = {}; for (var i = 0; i < arr.length; i++) { if (!json[arr[i]]) { res.push(arr[i]); json[arr[i]] = 1; } } return res; } unique([1, 3, 4, 3, 2, 1, 4, 6, 2]);//=> [1,3,4,2,6]
2、对象深复制
常见的可以使用JSON.parse()来进行复制:
function deepCopy(obj) { return JSON.parse(JSON.stringify(obj)); }
3、颜色格式转换
RGB转16进制:
function rgbToHex(rgb) { var s = "#"; for (var i = 0; i < 3; i++) { var c = Math.round(rgb[i]).toString(16); if (c.length == 1) c = '0' + c; s += c; } return s; } rgbToHex([24, 124, 255]);
16进制转RGB:
function hexToRgb(color) { var r = parseInt(color.substr(1, 2), 16); var g = parseInt(color.substr(3, 2), 16); var b = parseInt(color.substr(5, 2), 16); return new Array(r, g, b); } hexToRgb('#187cff');
4、计算渐变色
给定渐变色的个数,计算两个颜色之间的渐变色
function Gradient(c1, c2, step) { var Gradients = []; var A = hexToRgb(c1); var B = hexToRgb(c2); for (var N = 0; N < step; N++) { let t = []; for (var c = 0; c < 3; c++) { t[c] = A[c] + (B[c] - A[c]) / step * N; } Gradients.push(rgb2hex(t)); } return Gradients ; } Gradient('#000000', '#ffffff', 3);
5、解析URL
function parseUrl(url) { var parser = document.createElement('a'); parser.href = url; var paramPart = parser.search.substr(1).split('&'); parser.query = paramPart.reduce(function (res, item) { var parts = item.split('='); res[parts[0]] = parts[1]; return res; }, { } ); var { protocol, hostname, port, pathname, search, hash, host, query } = parser; return { protocol, hostname, port, pathname, search, hash, host, query }; }