是否相等
Object.is(a, b) // 判斷兩個值是否完全相等赎瑰,比===強在+0-0羊瘩,NaN的判斷
對象淺拷貝
Object.assign(target, o2, o3, o4) // 將o234合并到target對象上俩檬,同名屬性替換
利用Set去重
[...new Set([1,2,3,4,5,5,5,5])]
返回去除小數(shù)后的值,等于1.111 | 0
Math.trunc(1.111) //1纲熏,
判斷一個數(shù)是正數(shù)還是負數(shù),-1負數(shù)妆丘,0,-0局劲,其他值反水NaN
Matn.sign(1.111) // +1飘痛,
遍歷鍵名,arr.keys()
var arr = ['a', 'b' ,'c' ,'d']
for(let index of arr.keys()) {
console.log(index)
}
遍歷值容握,arr.values()
var arr = ['a', 'b' ,'c' ,'d']
for(let index of arr.values()) {
console.log(index)
}
遍歷鍵值對宣脉,arr.entries()
var arr = ['a', 'b' ,'c' ,'d']
for(let index of arr.entries()) {
console.log(index)
}
是否包含某個值
[1, 2, 3].includes(2) // true
檢測是否含有
s.has(2) // 返回true/false
判斷是否是數(shù)字
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
EXAMPLE:
validateNumber('10'); // true
轉(zhuǎn)化金額格式
const toDecimalMark = num => num.toLocaleString('en-US');
EXAMPLE:
toDecimalMark(12305030388.9087); // "12,305,030,388.909"
四舍五入并指定位數(shù)
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
EXAMPLE:
round(1.005, 2); // 1.01
字符串轉(zhuǎn)化成數(shù)組形式
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
EXAMPLE:
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
限制字符長度,超出末尾顯示...
const truncateString = (str, num) =>
str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
EXAMPLE:
truncateString('boomerang', 7); // 'boom...'
只展示部分末尾字段剔氏,其余用符號隱藏
const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);
EXAMPLE:
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'
挑選出對象中需要的key/value
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
EXAMPLE:
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
重置修改對象的某個指定的key
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] }
}),
{}
);
EXAMPLE:
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
雙層嵌套數(shù)組轉(zhuǎn)化對象格式
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {});
EXAMPLE:
objectToPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]
objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}
對比兩個對象值塑猖,并進行合并
const merge = (...objs) =>
[...objs].reduce(
(acc, obj) =>
Object.keys(obj).reduce((a, k) => {
acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
return acc;
}, {}),
{}
);
EXAMPLE:
const object = {
a: [{ x: 2 }, { y: 4 }],
b: 1
};
const other = {
a: { z: 3 },
b: [2, 3],
c: 'foo'
};
merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
對比對象的value是否一樣
const equals = (a, b) => {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
if (a.prototype !== b.prototype) return false;
let keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
return keys.every(k => equals(a[k], b[k]));
};
EXAMPLE:
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
獲取URL參數(shù)
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
EXAMPLE:
getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
getURLParameters('google.com'); // {}
復(fù)制內(nèi)容到剪貼板
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
vue 瀏覽器打印事件
printLink(){
var el = document.getElementById("printEventName");
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('<style type="text/css"></style><div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0){document.body.removeChild(iframe);}
}
JavaScript通用日期時間格式化方法
function dateFormat(val, format) {
let date = new Date(val)
let o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小時
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
'S': date.getMilliseconds(), // 毫秒
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp(`(${k})`).test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return format
}
栗子:
var datetime = new Date().getTime()
var date1 = dateFormat(datetime, 'yyyy.MM.dd hh:mm:ss')
var date2 = dateFormat(datetime, 'yyyy-MM-dd hh:mm:ss')
var date3 = dateFormat(datetime, 'yyyy-MM-dd')
console.log(date1) // 2018.04.27 16:38:35
console.log(date2) // 2018-04-27 16:38:35
console.log(date3) // 2018-04-27
光標(biāo)所在位置插入字符,并設(shè)置光標(biāo)位置
@param {dom} 輸入框
@param {val} 插入的值
@param {posLen} 光標(biāo)位置處在 插入的值的哪個位置
setCursorPosition (dom,val,posLen) {
var cursorPosition = 0;
if(dom.selectionStart){
cursorPosition = dom.selectionStart;
}
this.insertAtCursor(dom,val);
dom.focus();
console.log(posLen)
dom.setSelectionRange(dom.value.length,cursorPosition + (posLen || val.length));
}
光標(biāo)所在位置插入字符
insertAtCursor(dom, val) {
if (document.selection){
dom.focus();
sel = document.selection.createRange();
sel.text = val;
sel.select();
}else if (dom.selectionStart || dom.selectionStart == '0'){
let startPos = dom.selectionStart;
let endPos = dom.selectionEnd;
let restoreTop = dom.scrollTop;
dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length);
if (restoreTop > 0){
dom.scrollTop = restoreTop;
}
dom.focus();
dom.selectionStart = startPos + val.length;
dom.selectionEnd = startPos + val.length;
} else {
dom.value += val;
dom.focus();
}
}
判斷是否滾動到最低
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
EXAMPLE:
bottomVisible(); // true
獲取當(dāng)前滾動位置
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
EXAMPLE:
getScrollPosition(); // {x: 0, y: 200}
滾動到頂部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
EXAMPLE:
scrollToTop();
獲取明天的日期
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return t.toISOString().split('T')[0];
};
EXAMPLE:
tomorrow(); // 2018-10-19 (if current date is 2018-10-18)