如何访问对象数组的属性?(Typescript)

v1uwarro  于 2023-04-22  发布在  TypeScript
关注(0)|答案(5)|浏览(202)
let array = [{id:1},{id:1},{id:1},{id:1},{id:1}];
console.log(array[0].id);

显示的ID不存在。?
我们需要定义array = [any];

2vuwiymt

2vuwiymt1#

你的问题有点混乱!
显示的ID不存在。?
数组[0].id将返回1;

wmvff8tz

wmvff8tz2#

你可以试试

console.log(array[0]['id']);
t3psigkw

t3psigkw3#

试试这个,会有用的

constructor(){
    let   array = [{id:1},{id:1},{id:1},{id:1},{id:1}];
    console.log(array[0].id )
  }
zynd9foi

zynd9foi4#

要访问对象数组中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")
f4t66c6m

f4t66c6m5#

试着用这个例子:

for (let i = 0; i < array.length; i++){
    console.log(array[i].id);
}

相关问题