String的扩展方法
模板字符串
ES6新增的创建字符串的方式,使用反引号定义。
可以解析变量、换行、调用函数。
// let name = `这是一个模板字符串`;
// console.log(name);
let name = `张三`;
let say = `hello,我的名字叫${name}`;
console.log(say);
let result = {
name: 'zhangsan',
age: 20,
sex: '男'
}
//可以换行
let html = `<div>
<span>${result.name}</span>
<span>${result.age}</span>
<span>${result.sex}</span>
</div>`;
console.log(html);
//可以调用函数
const fn = () => {
return '我是fn函数'
}
// const fn = function () {
// return '一句话'
// }
let ht = `我是模板字符串${fn()}`
console.log(ht);
实例方法:startsWith()和endsWith()
startsWith():表示参数字符串是否在原字符串的头部,返回布尔值。
endsWith():表示参数字符串是否在原字符串的尾部,返回布尔值。
let str = 'hello ECMAScript 2020';
var re = str.startsWith('hello');
console.log(re); //true
let re2 = str.endsWith('2021');
console.log(re2); //false
实例方法:repeat()
表示将原字符串重复n次,返回一个新字符串。
console.log('x'.repeat(2)); //"xx"
console.log('hello'.repeat(2)); //"hellohello"
Set数据结构
ES6提供了新的数据结构 Set,它类似于数组,但成员都是唯一的,没有重复的值。
Set本身是一个构造函数,用来生成Set数据结构。
Set函数可以接收一个数组作为参数,用来初始化。
const s2 = new Set(['a', 'b']);
console.log(s2); //Set(2) {"a", "b"}
console.log(s2.size); //2 在当前数据结构当中包含了多少值
成员都是唯一的:
const s3 = new Set([1, 2, 3, 4, 4]);
console.log(s3); //Set(4) {1, 2, 3, 4}
可用于数组去重:
//数组去重
const s4 = new Set(['a', 'a', 'b', 'b']);
console.log(s4.size);
const arr = [...s4];
console.log(arr); //["a", "b"]
实例方法
add(value):添加某个值,返回 Set 结构本身
delete(value):删除某个值,返回一个布尔值,表示删除是否成功
has(value):返回一个布尔值,表示该值是否为 Set 的成员
clear():清除所有成员,没有返回值
const s4 = new Set();
//向set结构中添加值 ,使用add方法
s4.add('a').add('b').add('c');
console.log(s4.size); // 3
console.log(s4); // Set(3) {"a", "b", "c"}
//从set结构中删除值 用到的方法是delete
var r1 = s4.delete('c');
console.log(r1); // true
console.log(s4); //{"a", "b"}
console.log(s4.size); //2
//判断某一个值是否是set数据结构中的成员 使用has
const r2 = s4.has('a');
console.log(r2); //true
//清空set 数据结构中的值 使用clear方法
s4.clear();
console.log(s4.size); //0
遍历
Set 结构的实例与数组一样,也有forEach方法,用于对每个成员执行某种操作,没有返回值。
const s5 = new Set(['a', 'b', 'c']);
s5.forEach(value => {
console.log(value);
})