let array = [{id:1},{id:1},{id:1},{id:1},{id:1}];
console.log(array[0].id);
显示的ID不存在??
答案是我们需要定义array = [any];
答案 0 :(得分:0)
尝试一下:
for( let i=0;i<array.length;i++){
cosole.log(array[i].id);
}
答案 1 :(得分:0)
您的问题有点令人困惑!
显示的ID不存在??
array [0] .id将返回1;
答案 2 :(得分:0)
您可以尝试
console.log(array[0]['id']);
答案 3 :(得分:0)
这似乎是正确的,也许您没有正确输出值,请参见此处的代码:CODE
打字稿
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>
答案 4 :(得分:0)
尝试一下,它将起作用
constructor(){
let array = [{id:1},{id:1},{id:1},{id:1},{id:1}];
console.log(array[0].id )
}
答案 5 :(得分:0)
要访问对象数组中id
项的属性n-th
,可以执行以下操作:
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")