Javascript 仅当定义了属性时才推送
是否有方法修复此情况,以从推入else部分(而不是传递空字符串)中删除Javascript 仅当定义了属性时才推送,javascript,Javascript,是否有方法修复此情况,以从推入else部分(而不是传递空字符串)中删除标题 因此,如果title中的条件不满足,我只想按href。试试这个 const photo = { href: this.display_photos[index].path+this.display_photos[index].name, } if (this.display_photos[index].title) photo.title = this.display_photos[index].title
标题
因此,如果title
中的条件不满足,我只想按href
。试试这个
const photo = {
href: this.display_photos[index].path+this.display_photos[index].name,
}
if (this.display_photos[index].title)
photo.title = this.display_photos[index].title
photos.push(photo)
试试这个
const photo = {
href: this.display_photos[index].path+this.display_photos[index].name,
}
if (this.display_photos[index].title)
photo.title = this.display_photos[index].title
photos.push(photo)
我认为您只需要创建一个if/else条件来检查title是否定义如下:
const title=this.display_photos[index].title
const href=this.display_photos[index]。路径+this.display_photos[index]。名称
if(title)photos.push({title:title,href:href});
else photos.push({href:href})代码>我认为您只需要创建一个if/else条件来检查标题是否定义为这样:
const title=this.display_photos[index].title
const href=this.display_photos[index]。路径+this.display_photos[index]。名称
if(title)photos.push({title:title,href:href});
else photos.push({href:href})代码>此代码解决了我的问题。然而,由于我在这方面还不太熟悉,定义const
是否意味着只要应用程序运行,它就会一直存在?如果是这样,我可以将其定义为var
?这意味着您不能为变量分配新值。var最好不要使用,如果你不喜欢const,你也可以使用let。它不是关于喜欢const
,我要使用它,我只是好奇它的生命周期是什么:)只要应用程序在运行并且它们还在使用,所有变量都会留在内存中,这样垃圾收集就不会删除它们。所以将一个值定义为const、let或var对它的“生存期”没有影响。@Shilly感谢您的解释!关于var
,为什么“最好不要使用”?这段代码解决了我的问题。然而,由于我在这方面还不太熟悉,定义const
是否意味着只要应用程序运行,它就会一直存在?如果是这样,我可以将其定义为var
?这意味着您不能为变量分配新值。var最好不要使用,如果你不喜欢const,你也可以使用let。它不是关于喜欢const
,我要使用它,我只是好奇它的生命周期是什么:)只要应用程序在运行并且它们还在使用,所有变量都会留在内存中,这样垃圾收集就不会删除它们。所以将一个值定义为const、let或var对它的“生存期”没有影响。@Shilly感谢您的解释!关于var
,为什么“最好不要使用”?