![](/img/trans.png)
[英]How do you access a single property in an array of objects in Angular 6 typescript?
[英]How can we access a property of array of objects? (Typescript)
let array = [{id:1},{id:1},{id:1},{id:1},{id:1}];
console.log(array[0].id);
它显示的 id 不存在。?
答案是我们需要定义 array = [any];
尝试这个:
for( let i=0;i<array.length;i++){
cosole.log(array[i].id);
}
你的问题有点混乱!
它显示的 id 不存在。?
array[0].id 将返回 1;
你可以试试
console.log(array[0]['id']);
这似乎是正确的,也许您没有正确输出值,请参阅此处的代码: CODE
Typescript
array_t(){
let array = [{id:1},{id:5},{id:1},{id:1},{id:1}];
return array[0].id.toString() + array[1].id.toString();
}
array(){
let array = [{id:1},{id:5},{id:1},{id:1},{id:1}];
return array[0].id + array[1].id;
}
HTML
<br>
<div>{{ array() }}</div>
<br>
<div>{{ array_t() }}</div>
试试这个,它会工作
constructor(){
let array = [{id:1},{id:1},{id:1},{id:1},{id:1}];
console.log(array[0].id )
}
要访问对象数组中n-th
项的属性id
,您可以执行以下操作:
a[n].id
// or
a[n]['id']
要检查数组中n-th
项是否undefined
(也就是不存在),在访问id
属性之前,您可以使用:
a[n] && a[n].id
// or if you want a default value in case it doesn't exist
a[n] ? a[n].id : "not found"
要打印值,您可以使用console.log
。
请看代码片段
const array = [{id: 1}, {id: 1}, {id: 1}, {id: 1}, {id: 1}]; // Accessing element in position 0 console.log(array[0]); // Accessing the id of the element in position 0 console.log(array[0].id) console.log(array[0]['id']) // Accessing the id of the element in position 0 after checking its existence console.log(array[0] && array[0].id) // Accessing the id of the element in position 0 after checking its existence // and returning a default value if it is not defined console.log(array[0]? array[0].id: "not found") // Same as above but with an undefined value console.log(array[99]? array[99].id: "not found")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.