数值扩展
ES6
-
二进制和八进制
ES5中
将十进制转为二进制(使用toSting(),本身是转为字符串的,使用参数可以起到改变进制的效果)
const num = 5;
console.log(a.toString(2)
二进制转为十进制(使用parseInt(),第一个参数为要转换的数字,可以转为整型。如果使用第二个参数,就可以把当前的数当做几进制然后转化)
const b = 101;
console.log(parseInt(b,2);
对二进制和八进制的表示(加前缀,二进制0B,八进制0O)
const a = 0B0101
const b = 0O0101
-
Number.isFinite()、Number.isNaN()
-
Number.parseInt()、Number.parseFloat()
-
数的显示问题
问题:0.1+0.2不等于0.3,这是为什么? -
Number.isInteger(),数的最大值和最小值
问题:整数最大值?最小值? -
Math.trunc()
-
Math.sign(),判断正负、0、NaN
-
Math.cbrt()
ES7
- 幂运算符(指数运算符),等价于Math.pow()
Math.pow(底数,指数)
Math.pow(num,n)
幂运算符(注意两个星号不能分开)
底数**指数
num ** n
字符串扩展
ES6
- 字符串的Unicode表示法
字符表示方式(不太常用):
\uxxxx 码点范围(码点0000~ffff)
\u{} 码点范围不限
\跟三个八进制数(000~777)也表示字符
\x跟两个十六进制数(00~ff)
- 字符串的遍历器接口
就是用for of遍历字符串。 - 模板字符串
带标签的模板字符串
`${}${}`
const foo= (a,b,c,d) => {
console.log(a);
console.log(b);
console.log(c);
console.log(d);
}
const name = 'CLeon';
const age = '22';
foo`Mine Name ist ${name},Ich bin ${age}`
输出为:
a是一个数组,是模板字符串中写好的几个部分'Mine Name ist'、',Ich bin'
b是name的内容
c是age的内容
d是undefined
- String.fromCodePoint()
将码点转化为字符。 - String.prototype.includes()
返回true/false,indexOf()返回下标。 - String.prototype.startsWith()、String.prototype.endWith()
是否以xxx开头或结尾,遍历中应该可以经常用到。 - String.prototype.repeat()
重复字符串,返回一个新的字符串。
ES8
- String.prototype.padStart()、String.prototype.padEnd()
padStart() 从前面开始填充,参数:填充之后目标字符串的长度、(可选)填充的字符串
padEnd() 从后面开始填充,参数:填充之后目标字符串的长度、(可选)填充的字符串
不传第二个参数,就默认以空格来填充。
使用场景:
1、
注意月份返回的是0~11
在这种日期显示时,我们希望将一位的月份或号补全为两位的。
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth()+1).toString().padStart(2,'0');
const day = (now.getDate()).toString().padStart(2,'0');
console.log(year,month,day);
2、
显示手机号或身份证号的后四位,其他的想用*来覆盖。
const tel = '13313760687';
const result = tel.slice(-4).padStart(tel.length,'*');
ES9
- 放松模板字符串文字限制
针对带标签的模板字符串放松了一些限制
就是在标签模板字符串中对于本来应该报错的Unicode码会返回一个undefined不会报错。对于普通的模板字符串还是会的。
const foo = arg =>{
console.log(arg);
}
foo`\u{61} and \unicode` 第二个Unicode码是错误的
ES10
- String.prototype.trimStart()(trimLeft())、String.prototype.trimEnd()(trimRight())
去掉字符串前面或后面的空格,感觉在输入账号密码或者搜索这类功能下会有较大需求。
trim()去掉前后空格