Es6 字符串和数值
字符串
子串的识别
ES6 之前判断字符串是否包含子串,用 indexOf 方法,ES6 新增了子串的识别方法。
- includes():返回布尔值,判断是否找到参数字符串。
- startsWith():返回布尔值,判断参数字符串是否在原字符串的头部。
- endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部。
以上三个方法都可以接受两个参数,需要搜索的字符串,和可选的搜索起始位置索引
let string = "apple,banana,orange";
string.includes("banana"); // true
string.startsWith("apple"); // true
string.endsWith("apple"); // false
string.startsWith("banana",6) // true
JSON.stringify(obj)将类型转换为字符串
注意项:
- 这三个方法只返回布尔值,如果需要知道子串的位置,还是得用 indexOf 和 lastIndexOf 。
- 这三个方法如果传入了正则表达式而不是字符串,会抛出错误。而 indexOf 和 lastIndexOf 这两个方法,它们会将正则表达式转换为字符串并搜索它
字符串重复
repeat():返回新的字符串,表示将字符串重复指定次数返回
console.log("Hello,".repeat(2)); // "Hello,Hello,"
- 参数是小数,向下取整
- 参数是 0 至 -1 之间的小数,会进行取整运算,0 至 -1 之间的小数取整得到 -0 ,等同于 repeat 零次
- 参数是 NaN,等同于 repeat 零次
- 参数是负数或者 Infinity ,会报错
- 传入的参数是字符串,则会先将字符串转化为数字,非数字字符串转为NaN
字符串补全
padStart:返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串
padEnd:返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串
以上两个方法接受两个参数,第一个参数是指定生成的字符串的最小长度,第二个参数是用来补全的字符串。如果没有指定第二个参数,默认用空格填充
console.log("h".padStart(5,"o")); // "ooooh"
console.log("h".padEnd(5,"o")); // "hoooo"
console.log("h".padStart(5)); // " h"
如果指定的长度小于或者等于原字符串的长度,则返回原字符串:
console.log("hello".padStart(5,"A")); // "hello"
如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串:
console.log("hello".padEnd(10,",world!")); // "hello,worl"
常用于补全位数:
console.log("123".padStart(10,"0")); // "0000000123"
模板字符串
模板字符串相当于加强版的字符串,用反引号 `,除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式,模板字符串中的换行和空格都是会被保留的
let a=2023;
let b=`你好,${a}!`;
//你好2023!
let string = `Hello'\n'world`;
// Hello
//world
数值的表示
二进制表示法新写法: 前缀 0b 或 0B 。
console.log(0b11 === 3); // true
console.log(0B11 === 3); // true
八进制表示法新写法: 前缀 0o 或 0O 。
console.log(0o11 === 9); // true
console.log(0O11 === 9); // true
方法
Number 对象新方法
Number.isFinite()
用于检查一个数值是否为有限的( finite ),即不是 Infinity
console.log( Number.isFinite(1)); // true
console.log( Number.isFinite(0.1)); // true
// NaN 不是有限的
console.log( Number.isFinite(NaN)); // false
console.log( Number.isFinite(Infinity)); // false
console.log( Number.isFinite(-Infinity)); // false
// Number.isFinate 没有隐式的 Number() 类型转换,所有非数值都返回 false
console.log( Number.isFinite('foo')); // false
console.log( Number.isFinite('15')); // false
console.log( Number.isFinite(true)); // false
Number.isNaN()
用于检查一个值是否为 NaN 。
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN('true'/0)); // true
// 在全局的 isNaN() 中,以下皆返回 true,因为在判断前会将非数值向数值转换
// 而 Number.isNaN() 不存在隐式的 Number() 类型转换,非 NaN 全部返回 false
Number.isNaN("NaN"); // false
Number.isNaN(undefined); // false
Number.isNaN({}); // false
Number.isNaN("true"); // false