简体   繁体   中英

How to push an item into my array if the item doesn't exist?

I'm trying to push in an image if my array index doesn't contain a URL (or it's empty).

I'm using an if statement but am having issues pushing in the item.

if( typeof data[t].fullPicture === 'undefined' || data[t].fullPicture === null ){
      console.log(t + "Pushing png")
      data[t].push({fullPicture : "https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png"})
    }

What would be the best way to push in the item if it doesn't exist?

Try this ( Instead of pushing the data, update the value of the key):

 if(data[t].fullPicture === 'undefined' || data[t].fullPicture === null) { data[t].fullPicture = "https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png" }; 

@Jim Nilsson有正确的答案。

data[t].fullPicture = "https://upload.wikimedia.org/etc..."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM