ES6中字符串的方法和其他

ES6中字符串的方法和其他

  1. 字符串方法
  2. Map
  3. class类
  4. symbol

一、字符串方法

  1. repeat()
  2. includes()
  3. startwith()
  4. endwith()
  5. 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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值