ES6中字符串的方法和其他
- 字符串方法
- Map
- class类
- symbol
一、字符串方法
- repeat()
- includes()
- startwith()
- endwith()
- trim()
1.repeat()用于返回重复字符串参数为重复的次数
const str="hello world"
let result=str.repeat(2)
console.log(result)//hello worldhello world
2.includes()用于判断是否存在目标字符,存在返回true不存在返回false
const str="hello world";
let result=str.includes("he");
console.log(result)//true
3.startWith()判断是否以什么开头
const str="hello world";
let result=str.startsWith("he");
console.log(result)//true
4.endWith()判断是否以什么结尾
const str="hello world";
let result=str.endsWith("he");
console.log(result)//false
5.trim()用于去除首尾字符串的空格
const str=" helloworld "
let result=str.trim(str)
console.log(result);//helloworld
二、数据类型Map
对原本的对象类型,加强,原本key只可能是字符串,map类型可以让任意类型的数据作为key
如果需要往里面添加和读取,需要使用set和get方法
如果需要往里面读取和删除,需要使用has和delete方法
const obj={
name:"小明",
age:18
}
let m=new Map();
m.set(obj,1);
console.log(m.get(obj))
console.log(m)
三、class类
之前的js没有类这个概念,所以创建对象的时候只能使用构造函数创建
在constructor中写入属性,在class里写方法,直接实例化能快速创建对象
class People{
constructor(name,age,height){
this.name=name;
this.age=age;
this.height=height
}
run(){
console.log("能跑")
}
}
let p1=new People("张三",21,190);
let p2=new People("李四",21,190);
如果要继承该类,需要使用extends来实现继承,如果是要调用父类的属性,要使用super才行
class Student extends People{
constructor(name,age,height,score){
// 在继承中有一个super方法用来调用父级的构造函数
super(name,age,height);
// super必须写在自己属性的上方
this.score=score;
}
showInfo(){
console.log(this.name)
}
// 如果想重构父级的方法,直接重新写就能覆盖
run(){
console.log(this.name+"正在跑")
}
}
这样创建的方法比较简单,比混合继承看起来更加清晰,创建在类里的方法是直接挂载到原型上的不需要再使用prototype来减少内存,而且也能直接使用instanceof判断类名
四、symbol
独一无二的值,防止出现命名的冲突问题,用于作为对象的key的值
let s=Symbol("123")
let s2=Symbol("123")
console.log(s===s2)//false
如果要使用symbol加入对象中需要使用中括号来加入
let n=Symbol("name");
let obj={
age:21
}
obj.n="张三"//对象n
obj[n]="张三"//Symbol("name")
console.log(obj)