ES6语法练习
发布于:2021-12-15 11:30:02
次阅读
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>ES6语法练习</title></head><style> #box{ height: 200px; width: 200px; background-color: #90D7EC; }</style><body><div id="box"></div><script> //常规函数 function test() { return '1111' } // function 换成 => 放在参数和函数体中间 // 1. 如果没有参数, 或有多个参数就需要使用 ()来定义参数列表 // 2. 如果有一个参数,可以不用() // 3. 如果函数体中只有一条语句, 可以不用{}, 就不用使用return 会自动加上 let test1 = () => '1111' console.log(test1()) // 箭头函数在返回对象时, 必须在对象外面加上() const fun = id =>({id:id, name:'zhangsn'}); console.log(fun(10).name); // 箭头函数没有自己的this,它的this是继承而来,默认指向在定义它时所处的对象(宿主对象)。 const box = document.getElementById('box'); box.onclick = function() { setTimeout(()=>{ console.log(this); //this指向#box这个div,不使用箭头函数就指向windows this.style.backgroundColor = 'red' }, 3000); } //filter 过滤器 //map 映射 //reduce 汇总 //筛选并计算大于等于10的数并打5折,然后求和 let goods = [30, 80, 50, 5, 3, 1, 60, 9]; let sum = goods.filter(n => n >= 10).map(n => n*0.5).reduce((s, n)=>s+n); console.log(sum); //startsWith 判断以什么字符串开头 //endsWith 判断以什么字符串结尾 let url = "https://www.lmonkey.com"; if(url.startsWith("https")) { console.log(url); }else{ console.log("不是以https开头的"); } if(url.endsWith('cn')) { console.log(url); }else{ console.log("不是以.cn结尾的URL"); } // 模板字符串(template string)是增强版的字符串,用反引号(`)标识。 // 它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。 let name = '好好学习' let names = `<h1 style="color:yellow">${name}</h1>` box.innerHTML = names; //解构赋值 // 左右两边结构必须一样 // 右边必须有值 // 声明和赋值不能分开 let [x, y] = [1, 2, 3]; //数组 console.log(x); console.log(y); let {age,myName} = {myName:'zhangsan', age:10, sex:'男'}; //对象 console.log(myName); console.log(age); //扩展运算符 // ...三点运算符 // 展开数组 // 默认参数 let arr1 = [1,2,3]; let arr2 = [4,5,6] let arr = [...arr1,7,8,9, ...arr2]; console.log(arr);</script></body></html>