ES6(二)字符串、数值、对象
程序员文章站
2022-03-08 22:16:52
...
ES6(二)
ES6字符串
javaScipt只有indexOf()方法,
ES6新增了三种方法:
includes():返回布尔值,表示是否找到了参数字符串。
includes()方法是为了简化需求的判断
返回布尔值,true为找到了参数字符串
let str = "hello world!";
str.includes('he') //true
startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
返回布尔表示存在
let str = "hello world!";
str.startsWith('he'); //true
str.startsWith('ld'); //false
endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
返回布尔表示存在 endsWith()的参数用法跟其他两个不同,它针对的是前n个字符,而其他两个方法时从第n个位置直到字符串结尾
let str = "hello world!";
str.endsWith('he'); //false
str.endsWith('ld'); //true
ES6数值
数值的表示:
二进制:0b或0B
console.log(0b11 === 3); // true
console.log(0B11 === 3); // true
八进制:0o或0O
console.log(0o11 === 9); // true
console.log(0O11 === 9); // true
常量
允许指定默认值(当提取成员===undefined,默认值才会生效)
let [foo = true] = [];
foo // true
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
得到最大值:
max=Math.max.apply(null,array)
最小值
min=Math.min.apply(null,array)
对象
属性初始值的简写:
当一个对象的属性与本地变量同名时,不需要再写冒号和值,直接写属性名即可
这是ES5的赋值
let fullName = '杨三', age = 19;
let obj = {
fullName: fullName,
age: age
};
这是ES6的赋值
// 1. 当一个对象的属性与本地变量同名时,不需要再写冒号和值,直接写属性名即可。
let obj = {
fullName,
age
};
对象方法的简写:
// 在 ES 6 中,语法更简洁,取消了冒号和 function 关键字。如下所示:
let obj = {
fullName: '张三',
sayName () {
return this.fullName;
}
};
新增的两个方法:
Object.assign(target, source_1, ···)
用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)上:
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
Object.is(value1, value2)
Object.is()引入的目的就是为了保证在所有环境中,只要两个值是一样的,它们就应该相等,其行为与===基本一致,用来比较两个值是否严格相等。
Object.is('foo', 'foo')
// true
Object.is({}, {})
// false
上一篇: 《ECMAScript 6 入门》笔记(4) 字符串的新增方法
下一篇: es6类class