javascript - 在 js/ts 数组中,“any[]”是什么意思?
我现在正在学习 Angular2。在课程中我读到我必须将数据保存到“any”数组中,之后在示例中有这样的代码:
import { Component } from '@angular/core';
import { GithubService } from '../../services/github.service';
@Component({
selector: 'profile',
template: `<h1>Profile Component</h1>`,
})
export class ProfileComponent {
user:any[];
constructor(private _githubService:GithubService){
// this._githubService.getUser().subscribe(user => {console.log(user)});
this._githubService.getUser().subscribe(user => {
this.user = user;
});
}
}
代码 user:any[]; 意味着什么?我尝试在 Google、GitHub 等地搜索,但什么也没找到。甚至都不知道该读什么。
答案#1
首先需要知道的是,any[] 仅在 Typescript 中是有效的变量声明,在 Javascript 中无效。
这是一个两部分的声明——[] 在 Typescript 中用于声明一个值数组。any 用于声明数组中的条目可以是任何类型。相比之下,你也可以只为数组指定一种有效类型。例如,string[] 将声明一个 string 对象的数组。然后,Typescript 编译器会检查你是否只向数组中添加 string 对象。
答案#2
user: any; 意味着我们可以存储类型为 string、number、object、boolean 等的变量。
user: any[]; 意味着 user 必须是一个数组,并且数组元素的类型可以是字符串、数字、对象、布尔值等。