js中的数字
字符串转数字小技巧
使用+'123456'
即可
数字转换函数
- parseInt与parseFloat: 传入一个字符串,返回一个去掉多余字符的整数,第二个参数表示要解析的数字的基数
console.log(Number.parseInt('30px', 10));
console.log(Number.parseInt('e23', 10));//返回NaN
console.log(Number.parseInt(' 2.5rem '));
console.log(Number.parseFloat(' 2.5rem '));
- Number.isNaN():传入一个字符串或数字,检查是否为一个数字(not a numer),返回boolean
- Number.isFinite():同上,检查是否是数字
- Number.isInteger(): 检查是否为整数
Math和Rounding
- 计算开方
console.log(Math.sqrt(25));
console.log(25 ** (1 / 2));//幂运算
console.log(8 ** (1 / 3));
- max与min
console.log(Math.max(5, 18, 23, 11, 2));
console.log(Math.max(5, 18, '23', 11, 2));//正常
console.log(Math.max(5, 18, '23px', 11, 2));//报错
- math中也有固定值:如
Math.PI
- 随机数生成:
console.log(Math.trunc(Math.random() * 6) + 1);
限制随机数范围:
const randomInt = (min, max) =>
Math.floor(Math.random() * (max - min) + 1) + min;
// 0...1 -> 0...(max - min) -> min...max
// console.log(randomInt(10, 20));
-
Math.round:四舍五入
-
Math.ceil:向上取整
-
Math.floor(向下取整)
-
Math.trunc(直接截取)
-
浮点规范化:传入要保留几位,返回一个字符串
console.log((2.345).toFixed(2));
console.log(+(2.345).toFixed(2));
- 数字分割线使代码中的数字变易读:
const diameter = 287_460_000_000;
console.log(diameter);//不影响输出
BigInt
//64位最大表示
console.log(2 ** 53 - 1);
console.log(Number.MAX_SAFE_INTEGER);
//两种用法
console.log(4838430248342043823408394839483204n);
console.log(BigInt(48384302));
//计算
const huge = 20289830237283728378237n;
const num = 23;
console.log(huge * BigInt(num));
// Exceptions
console.log(20n > 15);
console.log(20n === 20);
console.log(typeof 20n);
console.log(20n == '20');
日期表示
用法合集:
//创建
const now = new Date();
console.log(now);
//传入字符串
console.log(new Date('Aug 02 2020 18:05:41'));
console.log(new Date('December 24, 2015'));
console.log(new Date(account1.movementsDates[0]));
//传入年月日。。。
console.log(new Date(2037, 10, 19, 15, 23, 5));
console.log(new Date(2037, 10, 31));
//按时间戳创建
console.log(new Date(0));
console.log(new Date(3 * 24 * 60 * 60 * 1000));
//常用方法
// Working with dates
const future = new Date(2037, 10, 19, 15, 23);
console.log(future);
console.log(future.getFullYear());
console.log(future.getMonth());
console.log(future.getDate());
console.log(future.getDay());//获取这是一周中的第几天
console.log(future.getHours());
console.log(future.getMinutes());
console.log(future.getSeconds());
console.log(future.toISOString());//日期标准形式
console.log(future.getTime());
//也可使用get方法
future.setFullYear(2040);
console.log(future);
日期可以进行计算,如:
可用于计算过了几天
const calcDaysPassed = (date1, date2) =>
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);
const days1 = calcDaysPassed(new Date(2037, 3, 4), new Date(2037, 3, 14));
console.log(days1);
国际化
- 使用
Intl.NumberFormat().format()
API,接受第一个参数为国家,第二个参数为格式可选选项,后传入format - 使用
new Intl.DateTimeFormat(locale).format(date);
更改时间格式 - 国家格式可使用浏览器自带语言格式来获取:
navigator.language
//数字
// Internationalizing Numbers (Intl)
const num = 3884764.23;
const options = {
style: 'currency',
unit: 'celsius',
currency: 'EUR',
// useGrouping: false,
};
console.log('US: ', new Intl.NumberFormat('en-US', options).format(num));
console.log('Germany: ', new Intl.NumberFormat('de-DE', options).format(num));
console.log('Syria: ', new Intl.NumberFormat('ar-SY', options).format(num));
console.log(
navigator.language,
new Intl.NumberFormat(navigator.language, options).format(num)
);
///时间
// Create current date and time
const now = new Date();
const options = {
hour: "numeric",
minute: "numeric",
day: "numeric",
month: "numeric",
year: "numeric",
// weekday: 'long',
};
// const locale = navigator.language;
// console.log(locale);
labelDate.textContent = new Intl.DateTimeFormat(
currentAccount.locale,
options
).format(now);
计时器
- setTimeout方法,传入一个回调函数,第二个参数为时间,以毫秒为单位,在时间到时执行回调函数,后面可以传入参数,这些参数最终可以使用于回调函数中
- clearTimeout():使计时器清除,传入计时器名称
const ingredients = ['olives', 'spinach'];
const pizzaTimer = setTimeout(
(ing1, ing2) => console.log(`Here is your pizza with ${ing1} and ${ing2} 🍕`),
3000,
...ingredients
);
console.log('Waiting...');
//
if (ingredients.includes('spinach')) clearTimeout(pizzaTimer);
循环执行:
- 设置时间间隔:
setInterval
,每隔设定时间长度,就执行一次 - 使用clearInterval()清除循环
// setInterval
setInterval(function () {
const now = new Date();
console.log(now);
}, 1000);
倒计时示例:
const startLogOutTimer = function () {
const tick = function () {
//时针和分针
const min = String(Math.trunc(time / 60)).padStart(2, 0);
const sec = String(time % 60).padStart(2, 0);
// 对UI进行更新
labelTimer.textContent = `${min}:${sec}`;
// When 0 seconds, stop timer and log out user
if (time === 0) {
clearInterval(timer);
labelWelcome.textContent = "Log in to get started";
containerApp.style.opacity = 0;
}
// Decrease 1s
time--;
};
// Set time to 5 minutes
let time = 120;
// Call the timer every second
tick();
const timer = setInterval(tick, 1000);
return timer;
};