ES6总结:数组和对象的结构,模块化等

1.数组解构

解构数组的方法

const arr = [100, 200, 300];
const [one, two, three] = arr;
console.log(one);//100
console.log(two);//200
console.log(three);//300

在数组解构语法中,我们****通过值在数组中的位置进行选取****,且可以存储在任意变量中,未显式声明的元素都会直接被忽略。在这个过程中,数组本身不会发生任何变化。

只解构想要获取的元素

const [,,mo]
console.log(mo);//300

解构赋值

数组解构也可用于赋值上下文

a=1;
b=2;
const [a,b]=arr;
console.log(a);//100
console.log(b);//200

在数组中,可以通过…语法将数组中的其余元素赋值给一个特定的变量,并且以数组的形式返回结果

let colors = ["red","green","blue"];
let [firstColor,...restColors] = colors;
console.log(firstColor);//"red"
console.log(restColors.length);//2
console.log(restColors[0]);//"green"

注意:在被解构的数组中,*不定元素必须为最后一个条目*,在后面继续添加逗号会导致程序抛出语法错误。

如果解构位置的成员个数小于被解构的数组长度,那么就会按照从前到后的顺序去提取

const arr = [100, 200, 300];
const [f]=arr
console.log(f);//100

反之,如果结构位置的成员个数大于被解构的数组长度,那么就会返回undefined

const arr = [100, 200, 300];
const[one, two, three,more]=arr
console.log(more)//undefined

如同访问数组中一个不存在的下标

如果没有查询到元素的值,那么就会返回默认值;如果能查询到,那就还是返回原值

const arr = [100, 200, 300];
const[one, two, three=123,more="default value"]=arr
console.log(three)//123
console.log(more)//default value

拆分字符串

const path = '/foo/bar/baz';
const [, rootdir] = path.split('/');
console.log(rootdir)//baz
const [rootdirs,] = path.split('/');
console.log(rootdirs)//foo

嵌套数组解构

let colors = ["red",["green","lightgreen"],"blue"];
let [firstColor,[secondColor]] = colors;
console.log(firsrColor);//"red"
console.log(secondColor)//green
2.对象解构

大部分性质和数组的解构差不多,但唯独注意一点

当外面定义的变量和对象里的属性名重名时,应该采取这种方法去解决

const obj = {name:'zce',age:18};
const {name} = obj;
console.log(name);//zce
const name = 'tom';
const {name :objName} = obj;
console.log(objName);

嵌套对象解构

let node = {
    type:"Identifier",
    name:"foo",
    loc:{
        start:{
          line:1,
          column:1
        },
        end:{
          line:1,
          column:4
        }
    }
};
 
let {loc:{start}} = node;
console.log(start.line);//1

在这个示例中,我们在解构模式中使用了花括号,其含义为在找到node对象中的loc属性后,应当深入一层继续查找start属性

3.模板字符串
const person = {
  username: 'Jan',
  age: 21,
  sex: 'male'
};

一般字符串

const info='我的名字是:' +
  person.username +
  ', 性别:' +
  person.sex +
  ', 今年' +
  person.age +
  '岁了';
console.log(info);//我的名字是Jan,性别:male,今年21

模板字符串

const info = `我的名字是:${person.username}, 性别:${person.sex}, 今年${person.age}岁了`;
console.log(info);
//我的名字是Jan,性别:male,今年21岁了

输出多行字符串

方式一:
const info=`第一行\n第二行`;
方式二:
const info=`第一行
     第二行`;//这里前面会有空格

输出`和\等特殊字符

const info=`\`\\`;//需要转义
console.log(info)//`\

模板字符串的注入

模板字符串中嵌入变量,要将变量名写在${}之中。大括号内可以放入任意的JavaScript表达式,可以进行运算,以及引入对象属性。

const username = 'Jan';
const person = { age: 21, sex: 'male' };
const getSex = function (sex) {
  return sex === 'male' ? '男' : '女';
};
const info = `${username}, ${person.age},${getSex(person.sex)}`;
console.log(info);//Jan,21,女
const value=`${1+2}`;
console.log(value);//3

只要最终可以得出一个值的就可以通过 ${} 注入到模板字符串中

4.字符串的扩展方法
const message="Error:foo is not defined"
//startWith(),判断是否以某个字符串开头
console.log(message.startsWith("Error"))//true
//endsWith()判断是否以某个字符串结尾
console.log(message.endsWith("."))//true
//includes()判断是否包含某个字符串
console.log(message.includes("foo"))//true

字符串的遍历器接口

for(let item of "cyl"){
    console.log(item);
}//c,y,l

repeat 方法返回一个新字符串,表示将原字符串重复n次

"x".repeat(3)//"xxx"
//参数如果是小数,会被取整
"x".repeat(2.9)//xx

如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全

'x'.padStart(5,"ad");//adadx
'x'.padEnd(4,"ad");//xada
"x".padStart(4);//"   x"
5.参数默认值

函数参数的默认值:函数没有传递形参时,默认使用的值

//enable=true,形参默认值,只会在没有传递实参,或者为undefind时才会使用
function foo(enable=true){
    console.log(enable);
}
foo();//true
foo(false);//false
//当有多个形参时,带有默认值的形参一定要出现在参数列表的最后,因为参数是按照次数传递的
function foo1(bar,enable=true){
    
}

6.剩余(rest)参数
//...args会以数组的形式去接受,从当前这个位置开始,往后所有的形参
function foo(...args){
    console.log(args)
}
foo(1,2,3)//[1,2,3]
7.展开数组参数
const arr=["foo","bar","baz"]
console.log(...arr);//foo bar baz
8.箭头函数

箭头函数是匿名函数,允许我们用更短的语法定义函数。

传统函数:

function sum(a,b){
    return a+b;
}

箭头函数

const sum=(a,b)=>a+b
//没有参数
const sum=()=>console.log("123")
//方法体有多条语句
const f=()=>{
    //结果需要用return返回
}
const users = [
   {
      name: "John",
      age: 24
   },
   {
      name: "Jane",
      age: 32
   },
   {
      name: "Blake",
      age: 12
   }
]

选择18岁以上的用户

//user相对于users数组里面的每个user
const adults=users.filter(user=>user.age>18)

箭头函数没有自己的this

箭头函数中的this实际是外层函数的this(箭头函数的this对象是定义时所在的对象,而不是使用时的对象)

箭头函数最大的一个好处就是它的 this指向定义时所在环境的 this ,而非使用时环境的 this,比如在SetTimeeout 函数的回调函数中,如果使用箭头函数,那么THIS还是指向调用 SetTimeeout 的对象里的this

function Timer() {
  this.s1 = 0; 
  this.s2 = 0;
  // 箭头函数
  setInterval(() => this.s1++, 1000);
 
  // 普通函数
  setInterval(function () {
    this.s2++;
  }, 1000);
}
 
var timer = new Timer();
 
setTimeout(() => console.log('s1: ', timer.s1), 3100); // s1: 3
setTimeout(()=>console.log('s2: ',timer.s2),3100)//0

箭头函数永远指向上下文的this

9.对象字面量增强
const bar="345"
const obj={
    foo:123,
    //bar:bar,相同的名字可以省略
    bar,
    method1(){
        console.log("method")
    },
    //随机属性名,方括号里面的结果会作为属性名
    [Math.random()]:123
}
obj.method1();
10.class类
class Person{
    constructor(name){
        this.name=name;
    }
    say(){
        console.log(`hi,my name is ${this.name}`)
    }
    static setName(name){
      return new Person(name);
    }
}
const p=new Person("Jan");
p.say();//hi,my name is Jan
//static 方法,不属于某个对象,而是属于类,可以直接使用类型调用
Person.setName("Jan");
//继承
Class student extends Person{
    constructor(name,number){
        super(name)
        this.number=number;
    }
    hello(){
        super.say()
        console.log(`my school number is ${this.number}`)
    }
}
const s=new Student("Jan",12323);
s.hello();//hi,my name is Jan,my school number is 12323
11.set和Map 数据结构

set

const s=new Set();
s.add(1).add(2).add(3).add(2)
console.log(s)//{1,2,3}
//遍历
for(let i of s){
    console.log(i);
}
//s.size():长度,
s.has(1)//true,判断元素是否在集合中
s.delete(3)//删除3
s.clear()//清空s
const arr=[1,2,1,3,4,1]
//对arr进行去重
const result=new Set(arr);
console.log(result)

Map:以键值对的形式存在

const map = new Map([
  ['name', '张三'],
  ['title', 'Author']
]);
map.set("age","21");//添加元素
map.size // 3
map.has('name') // true
map.get('name') // "张三"
map.has('title') // true
map.get('title') // "Author"
//遍历Map
//方法一
map.forEach(function(value,key,map){
    console.log(key+":"+value);//name:张三...
})
//方法二
for(let [key,value] of map){
    console.log(key,value)
}
12. 数组的扩展方法

Array.from()方法

  • 将数组对象装换为真正的数组

      let person = {
                0: 'cyl',
                1: '21',
                2: '女',
                3: ['jane', 'john', 'Mary'],
                'length': 4
            }
            let arr = Array.from(person)
            console.log(arr) // ['cyl','21','女',['jane','john','Mary']]
    

    注:

    1、该类数组对象必须具有length属性,用于指定数组的长度。如果没有length属性,那么转换后的数组是一个空数组。
    2、该类数组对象的属性名必须为数值型或字符串型的数字
    ps: 该类数组对象的属性名可以加引号,也可以不加引号

    • 将set结构的数据转换为真正的数组
    let arr=[1,2,3,4]
    let set=new Set(arr);//将数组转换为set集合
    console.log(Array.from(set))//[1,2,3,4]
    

Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如下:

let arr=[1,2,3,4]
arr.map((item,index)=>{
    console.log(item+1);//2,3,4,5
})
let set =new Set(arr);
console.log(Array.from(set,item=>item+1))//[2,3,4,5]
  • 将字符串转换为数组

    string="abc";
    console.log(Array.from(string));//["a","b","c"]
    

    find()和findIndex()

    数组实例的find方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined

    [1, 4, -5, 10].find((n) => n < 0)
    // -5
    [1, 5, 10, 15].find(function(value, index, arr) {
      return value > 9;
    }) // 10
    

    数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1

    [1, 5, 10, 15].findIndex(function(value, index, arr) {
      return value > 9;
    }) // 2
    

    fill()

    fill方法使用给定值,填充一个数组。

    ['a', 'b', 'c'].fill(7)
    // [7, 7, 7]
    //fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置
    ['a', 'b', 'c'].fill(7, 1, 2)
    // ['a', 7, 'c']
    

    entries(),keys(),values()

    ES6 提供三个新的方法——entries()keys()values()——用于遍历数组keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
13.Moudle
  • 基本导入导出

    基本导出:类似于 exports.xxx = xxxx ,基本导出可以有多个,每个必须有名称基本导出的语法如下:

    export 声明表达式 
    或 
    export {具名符号} 
    

    基本导入:由于使用的是依赖预加载,因此,导入任何其他模块,导入代码必须放置到所有代码之前。对于基本导出,如果要进行导入,使用下面的代码

    import { 导入的符号列表 } from "模块路径"; 
    

    实例:

    <!DOCTYPE html>
    <html lang="zh-CN">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
      <body>
        <script src="./test1.js" type="module"></script>
        <script src="./test2.js" type="module"></script>
      </body>
    </html>
    
    //test1.js,导出
    export var name="cyl";
    export function fn(){
        console.log("test1")
    }
    var age=21;
    var sex="male";
    export{age,sex};
    //test2.js,导入
    import {name,age,sex,fn} from "./test1.js"
    console.log(name)//cyl
    fn();//test1
    
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值