Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何改进用于检查数组空性的代码?_Javascript_Typescript - Fatal编程技术网

Javascript 如何改进用于检查数组空性的代码?

Javascript 如何改进用于检查数组空性的代码?,javascript,typescript,Javascript,Typescript,当数组为空时,对象的“id”必须为=1,然后添加到数组中的对象,如果数组不为空,则添加了对象,并且现有id为+1。如何改进此代码 添加方法: addPost(title: string, url: string): void { if (this.collection.length == 0) { const post:Picture = { title, url, id: 1

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

我将使用条件运算符提前计算出
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);
}

如果
length
0
它将变成
0+1
,否则它将成为最后一个
id
+1

摆脱
id
,因为它与数组索引基本上是冗余的…?!或者至少,
id:this.collection.length+1
?@deceze可以删除帖子(例如,添加第一个->id 0,添加第二个->id 1,首先删除,添加另一个->id 2id以删除一个数组为方便起见,获取
id
的整个逻辑可以进一步拆分为单独的函数,因此您只需执行
const id=getNextId()
const id = (this.collection.length && this.collection[this.collection.length - 1].id) + 1;
const post: Picture = { title, url, id };
this.collection.unshift(post);