Javascript的一些方法總結 ---->毒牙
1、正則匹配電話格式
if(!/(^1[3|5|7|8][0-9]{9}$)/.test(你要驗證的參數)) {
// TODO
}
2、解決toFixed()的bug
(Math.round(param * 100) / 100).toFixed(2)
3 金錢千位分錢符號 + 保留兩位小數
/*
* @Author: 毒牙
* @Last Modified by: 毒牙
* @desc 金錢符號轉換 && 保留兩位小數(四捨五入)
*/
function transformatMoney(money) {
money = new Number(money) ? (Math.round(money * 100) / 100).toFixed(2) : "0.00";
return money.toString().replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
return $1 + ",";
});
}
4、封裝時間格式
const FormatDate = {
//轉換爲yyyy-dd-mm
dateFormat(timestamp) {
timestamp = typeof timestamp === "number" ? timestamp : parseInt(timestamp)
let time = new Date(timestamp);
let year = time.getFullYear();
let month = time.getMonth() + 1;
let date = time.getDate();
return year + '-' + addZero(month) + '-' + addZero(date);
},
//轉換爲yyyy-MM-dd HH-mm-ss
timeFormat(timestamp) {
timestamp = typeof timestamp === "number" ? timestamp : parseInt(timestamp)
let time = new Date(timestamp);
let year = time.getFullYear();
let month = time.getMonth() + 1;
let date = time.getDate();
let hours = time.getHours();
let minutes = time.getMinutes();
let seconds = time.getSeconds();
return year + '-' + addZero(month) + '-' + addZero(date) + ' ' + addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds);
}
}
// 補0
function addZero(m) {
return m < 10 ? '0' + m : m
}
5、every()
用於檢測數組所有元素是否都符合指定條件
6、from()
用於通過擁有 length 屬性的對象或可迭代的對象來返回一個數組。
7、isNaN()
用於檢查其參數是否是非數字值
8、漢字排序
var x = ['du', 'ya']
x.concat([]).sort((a,b)=>a.localeCompare(b))
9、instanceof
instanceof運算符用於測試構造函數的prototype屬性是否出現在對象的原型鏈中的任何位置
10、setTimeout(() => {}, 0)的作用
異步線程 在同步線程後執行