// 对象 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'; }
让数字的字面值看起来像对象
toString(); // Uncaught SyntaxError: Invalid or unexpected token ..toString(); // 第二个点号可以正常解析 .toString(); // 注意点号前面的空格 (2).toString(); // 2先被计算
对象可计算属性名(仅在ES6中)
var suffix = ' name'; var person = { ['first' + suffix]: 'Nicholas', ['last' + suffix]: 'Zakas' } person['first name']; // "Nicholas" person['last name']; // "Zakas"
数字四舍五入
// v: 值,p: 精度 function (v, p) { p = Math.pow(10, p >>> 31 ? 0 : p | 0) v *= p; return (v + 0.5 + (v >> 31) | 0) / p } round(123.45353, 2); // 123.45
在浏览器中根据url下载文件
function download(url) { var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (isChrome || isSafari) { var link = document.createElement('a'); link.href = url; if (link.download !== undefined) { var fileName = url.substring(url.lastIndexOf('/') + 1, url.length); link.download = fileName; } if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } if (url.indexOf('?') === -1) { url += '?download'; } window.open(url, '_self'); return true; }
快速生成UUID
function uuid() { var d = new Date().getTime(); var uuid = 'xxxxxxxxxxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; }; uuid(); // "33f7f26656cb-499b-b73e-89a921a59ba6"
JavaScript浮点数精度问题
function isEqual(n1, n2, epsilon) { epsilon = epsilon == undefined ? 10 : epsilon; // 默认精度为10 return n1.toFixed(epsilon) === n2.toFixed(epsilon); } 0.1 + 0.2; // 0.30000000000000004 isEqual(0.1 + 0.2, 0.3); // true 0.7 + 0.1 + 99.1 + 0.1; // 99.99999999999999 isEqual(0.7 + 0.1 + 99.1 + 0.1, 100); // true
内容版权声明:除非注明,否则皆为本站原创文章。