es6 提取数组对象一部分_详解 ES6 解构

fe6e4a75ae1add0fc6c65f20023f122b.png

在 Angular 中,你会看到这样的语法:

import { Component } from '@angular/core';

我们把 { things } 这部分的写法加做解构,这是ES6和TypeScript提供的特性。
在 ES6 中,你可以使用解构从数组和对象中提取值并赋值给独特的变量。

ES6 之前是如何提取数组的值

const point = [10, 20, 30]

const x = point[0];
const y = point[1];
const z = point[2];

console.log(x, y, z) // log 10, 20, 30

ES6 之前是如何提取对象中的值

const people = {
  name: 'Johnson',
  age: 30
}

const name = people.name;
const age = people.age;

console.log(name, age) // log Johnson, 30

解构

解构数组中的值:[]表示被解构的数组,x, y, z 表示要将数组中的值存储在其中的变量。

const point = [10, 20, 30];

const [x, y, x] = point;

console.log(x, y, x)

// 还可以忽略值,可以这样
const [x, , z] = point;

解构对象中的值:
花括号{}表示被解构的对象,nage, age 表示要将对象中的属性存储到其中的变量,无需指定要从其中提取值的属性。

const people = {
  name: 'Johnson',
  age: 30
}

const { name, age } = people;

console.log(name, age) // log Johnson, 30
你还可以指定在解构对象时要选择的值。例如 let { name } = people

再回头看看 Angular 的代码:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

你就明白,import导入了 Angular 核心的 Component 接口,在装饰器中的元数据selector, templateUrl, styleUrls就要遵守接口的规范,类型不对,检查会出现错误,编译也不会通过。

// node_modules/@angular/core/src/metadata/directives.d.ts
export interface Component extends Directive {
    changeDetection?: ChangeDetectionStrategy;
    viewProviders?: Provider[];
    moduleId?: string;
    templateUrl?: string;
    template?: string;
    styleUrls?: string[];
    styles?: string[];
    animations?: any[];
    encapsulation?: ViewEncapsulation;
    interpolation?: [string, string];
    entryComponents?: Array<Type<any> | any[]>;
    preserveWhitespaces?: boolean;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值