Angular Typescript静态只读
我试图在我的代码中使用静态只读,但我从未做过这样的事情。我知道我能做到:Angular Typescript静态只读,angular,typescript,find,Angular,Typescript,Find,我试图在我的代码中使用静态只读,但我从未做过这样的事情。我知道我能做到: export class Names { static readonly michael = { firstName: 'michael', secondName: 'jackson'}; static readonly john = { firstName: 'John', secondName: 'Doo'}; static readonly donald = { firstName: 'Don
export class Names {
static readonly michael = { firstName: 'michael', secondName: 'jackson'};
static readonly john = { firstName: 'John', secondName: 'Doo'};
static readonly donald = { firstName: 'Donald', secondName: 'Trump'};
}
我有
name = 'michael';
我需要的是搜索里面的名字,找到那个人就是Michael,并返回他的名字和姓氏,类似这样的东西
found = { firstName: 'michael', secondName: 'jackson'};
不要担心名称,因为我只是简化了一个问题,有人可以帮助我,没有名称,所有静态只读值都是唯一的。我知道我可以在数组中搜索,然后找到,但是如何在类中搜索呢?您可以试试这段代码
import { Component, OnInit } from '@angular/core';
import { Names } from './models/Names';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'angular-material';
name = 'michael';
constructor() { }
ngOnInit(): void {
if (Names[this.name]) {
console.log(Names[this.name]);
} else {
console.log('Not found');
}
}
}
您应该使用一个数组类型的静态只读变量来保存所有对象。基本上是一组对象:在角度上,这就是你要做的
import { Component, OnInit } from '@angular/core';
import { Names } from './models/Names';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class Names implements OnInit {
static readonly arrayOfObjects = [
{ firstName: 'michael', secondName: 'jackson'},
{ firstName: 'John', secondName: 'Doo'},
{ firstName: 'Donald', secondName: 'Trump'}
];
constructor() {
const filter = Names.arrayOfObjects.filter(object => object.firstName === 'michael')
console.log(filter)
}
}
要获取存储在
名称中的所有值,可以使用。然后您可以选择一个:
Object.values(Names).find(p => p.name === 'michael')
为什么不使用一个数组类型的静态只读变量来保存所有对象呢。基本上是一组物体?请你写下并回答,我们会看到的。如果问题是如何将其转换为数组-您可以只使用对象。值(名称)
这不是问题转换为数组,我需要搜索内部名称的函数,如果您知道答案,请提供,谢谢对象。值(名称)。查找(p=>p.name=='michael')
确定,如何访问john,如arrayOfObjects[1]。名字你是说你想找到john@Miomirdancevices,但直接访问不是Find你能解释一下,直接访问是什么意思吗?