如何改进检查数组是否为空的代码?

时间:2018-09-21 09:19:52

标签: javascript typescript

当数组为空时,对象的“ 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",
}];

2 个答案:

答案 0 :(得分:1)

我将使用条件运算符提前找出id,从而使您只需在代码中创建一次声明postunshift

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);

如果length0,它将变成0 + 1,否则它将成为最后的id + 1