|
生成指定范圍的隨機整數(shù) const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; randomIntegerInRange(0, 5); 生成指定范圍的隨機小數(shù) const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; randomNumberInRange(2, 10); 四舍五入到指定位數(shù) const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2);
精確小數(shù) const RoundNum = (num, decimal) =>Math.round(num * 10 ** decimal) / 10 ** decimal;const num = RoundNum(1.69, 1);// num => 1.7 簡單的貨幣單位轉換 const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
toCurrency(123456.789, 'EUR'); // €123,456.79
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79
toCurrency(123456.789, 'USD', 'fa'); // ??????????
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423
隨機十六進制顏色 const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
randomHexColorCode();
奇偶判斷 const OddEven = num => !!(num & 1) ? "odd" : "even";const num = OddEven(2);// num => "even" 統(tǒng)計數(shù)組成員個數(shù) const arr = [0, 1, 1, 2, 2, 2];const count = arr.reduce((t, v) => { t[v] = t[v] ? ++t[v] : 1; return t;}, {});// count => { 0: 1, 1: 2, 2: 3 }
數(shù)組中某元素出現(xiàn)的次數(shù) export function countOccurrences(arr, value) {
return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}
簡單數(shù)組交集 export const similarity = (arr1, arr2) => arr1.filter(v => arr2.includes(v)); 實現(xiàn)千位分隔符 // 保留三位小數(shù)
parseToMoney(1234.56); // return '1,234.56'
parseToMoney(123456789); // return '123,456,789'
parseToMoney(1087654.321); // return '1,087,654.321'
function parseToMoney(num) {
num = parseFloat(num.toFixed(3));
let [integer, decimal] = String.prototype.split.call(num, '.');
integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,');
return integer + '.' + (decimal ? decimal : '');
}
function parseToMoney(str){
// 僅僅對位置進行匹配
let re = /(?=(?!\b)(\d{3})+$)/g;
return str.replace(re,',');
}
驗證是否是身份證 function isCardNo(number) {
var regx = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return regx.test(number);
}
|
|
|