当数组为空时,对象的“ id”必须为= 1,然后将对象添加到数组中;如果数组不为空,则添加了对象,并且现有的id为+1。如何改进这段代码?
添加方法:
addPost(title: string, url: string): void {
if (this.collection.length == 0) {
const post:Picture = {
title,
url,
id: 1
};
this.collection.unshift(post);
} else {
const post:Picture = {
title,
url,
id: this.collection[this.collection.length - 1].id + 1
};
this.collection.unshift(post);
}
}
数组:
export const myCollection: Picture[] = [
{
id: 1,
title: "accusamus beatae ad facilis cum similique qui sunt",
url: "https://placekitten.com/200/198",
}];
答案 0 :(得分:1)
我将使用条件运算符提前找出id
,从而使您只需在代码中创建一次声明post
和unshift
:
addPost(title: string, url: string): void {
const id: number = this.collection.length
? this.collection[this.collection.length - 1].id + 1
: 0
const post:Picture = {
title,
url,
id
};
this.collection.unshift(post);
}
答案 1 :(得分:1)
const id = (this.collection.length && this.collection[this.collection.length - 1].id) + 1;
const post: Picture = { title, url, id };
this.collection.unshift(post);
如果length
是0
,它将变成0 + 1
,否则它将成为最后的id
+ 1
。