ES6语法学习(一)

强烈推荐的学习公众号

一直以来都有关注web前端开发这个公众号,里边会有些很实用的文章分享,强烈推荐哦!
公众号里有视频学习,很实用,通俗易懂!
在这里插入图片描述在这里插入图片描述

知识点记录

1. 标签模板字符串:

通过highlight处理模板字符串,返回我们想要的字符串

		function highlight(strings, ...arr){
			const handletag = arr.map(value => 
			`<span class="highlight">${value}</span>`
			);			
			return strings.reduce((pre,cur,i) => `${pre}${cur}${handletag[i] ||''}`,'');
		}
		
		const user = "Hanmei";
		const topic = "Learn to code";
		const sentence = highlight`${user} has comment on your topic ${topic}`;
		
		document.body.innerHTML = sentence;

2. 标签模板实际应用:

		<style>
		.add-comment{
			width: 500px;
		}
		.common-text{
			width:100%;
		}
		.comment-header{
			font-size:18px;
			color:#f00;
			border-bottom:1px solid #ddd;
			
		}
		.comment-body{
			font-size:12px;
			color:#999;
		}
		</style>
       <div class="container">
			<form class="add-comment">
				<textarea class="common-text"></textarea>
				<button type="button">post commnet</button>
			</form>
			<div class="comment"></div>
		</div>
		<script src="https://cdn.bootcdn.net/ajax/libs/dompurify/2.2.9/purify.js"></script>
		<script type="text/javascript">
		//获取Dom
		const addComment = document.querySelector('.add-comment');
		const textarea = document.querySelector('.common-text');
		const commentDiv = document.querySelector('.comment');
		const user = "Mary";
		//使用DomPurify过滤掉特殊字符,防止xxs攻击
		function sanitize(strings, ...values){
			const dirty = strings.reduce((pre,cur,i) => `${pre}${cur}${values[i] || ''}`,'');
			return DOMPurify.sanitize(dirty);
		}
		//监听按钮点击事件
		addComment.addEventListener('click', function(event){
			event.preventDefault();
			const newComment = textarea.value.trim();
			if(newComment){
				commentDiv.innerHTML = sanitize`
					<div class="comment-header">${user}</div>
					<div class="comment-body">${newComment}</div>
				`
				textarea.value = '';
			}
			
		})
		</script>

3. 使用字符串方法达到右对齐

新增的字符串方法:.startsWith().endsWith().includes().repeat()

			const id = "230231198908273127";
			const fan = 'I Love sports.';
			
			function padding(strings, length=25){
				return `${' '.repeat(Math.max(length - strings.length,0))}${strings}`;
			}
			console.log(padding(id));
			console.log(padding(fan));

在这里插入图片描述

4. 对象解构

可以快速的从对象中提取所需要的属性,并且可以嵌套;
而当对象中的属性与已声明的变量重复时,也可以重新命名{mother:renameMother}
解构时的变量可以给默认值{brother='Tony Brother'},以防止赋值对象(Tony)中没有这个属性brother

            const Tony = {
				name:'Tony',
				age:'25',
				family:{
					mother:'Tony Moth',
					father:'Tony Father'
				}
			}
			
			let name = '';
			 //直接使用大括号,它会被解析成代码块
			 //这样的对象解构要用括号包起来
			({name , age} = Tony);
			console.log(name);   // Tony
			console.log(age);    // 25
			
			//想要获取嵌套对象
			let mother = '';
			const {mother:renameMother,father,brother='Tony Brother'} = Tony.family;
			console.log(renameMother);    // Tony Moth  ,与声明变量冲突时可以重新定义
			console.log(father);    // Tony Father
			console.log(brother)   // Tony Brother  ,对象中未定义时,解构时可以给默认值

注意:
只有当Tony对象的属性是明确的undefined时,才使用解构中给的默认值,若果是null或是false都会是原来的值

		  // 创建元素例子
           function createDiv( options={} ){
				const {
					parent = 'body',
					width = '100px',
					height = '100px',
					background = 'red'
				} = options;
				
				const div = document.createElement('div');
				div.style.width = width;
				div.style.height = height;
				div.style.background = background;
				
				// document.querySelector(parent).appendChild(div);
				document.querySelector(parent).append(div)
				
			}
			
			createDiv({
				width:'200px',
				height:'200px',
				background:'blue'
			})

5. 数组解构

            const arr = ['apple','banana','grape'];
			const [arg1, ...rest] = arr;
			console.log(arg1, rest);
			
			//数组解构的实际应用:交换变量
			let a = 1;
			let b = 2;
			[a,b] = [b,a]; 
			console.log(a,b);

在这里插入图片描述

6.循环

循环方法利弊
for繁琐
forEach不能终止/跳过(breakcontinuereturn 都不生效)
for in遍历的是属性名(index), 列举的都是对象的可枚举属性
for of遍历的是属性值(value),不会遍历数组上的非数字属性,支持循环终止/跳过;
可用于遍历数组arguments对象、字符串NodeListmapset,但目前不支持 object
1 ) for in 详解

从下面两段代码中,可看出for in 循环既能得到value值,也能得到index值。

            const arr = ['apple','banana','grape'];
			for(let fruit of arr){
				console.log(fruit);
			}

执行next方法返回的是Object,对象中有两个值:donevalue
在这里插入图片描述

            /**
            * entries是遍历器接口,内部有next()方法
            * 可以如上图中,手动遍历数组,for of 是帮我们自动执行next方法了
            * 遍历 arr.entries() 可以一起得到value和index
            **/
            const arr = ['apple','banana','grape'];
			for(let fruit of arr.entries()){
				console.log( fruit, fruit[1]);
			}

在这里插入图片描述


2 ) for in 实用案例
          // 遍历 arguments
			function sum(){
				console.log(arguments);
				let total = 0;
				for(let num of arguments){
					total = total + num;
				}
				console.log(total);
				return total;
			}
			sum(10,20,30,40,50);
			
			// 遍历字符串
			let strings = 'wuyiahaha';
			for(let str of strings){
				console.log(str);
			}
			
			// 遍历NodeList
			const lis = document.querySelectorAll('li')
			console.log(lis);
			for(let li of lis){
				console.log(li);
				li.addEventListener('click',function(){
					li.classList.toggle('active');
				})
;			}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值