如何在数组元素无指定属性时添加内容?代码问题咨询
Hey there! Let's break down what's going wrong here and get your code working right.
First off, the problem with your current code is that you're using push() on an object (data[t]), but push() is a method exclusively for arrays. Objects don't have this method, which is why your push operation is failing.
The Correct Way to Add/Update Object Properties
To add or set the fullPicture property on your object, you just need to assign it directly using dot notation. Here's how to fix your original code:
// Check if fullPicture is undefined, null, or empty string if (typeof data[t].fullPicture === 'undefined' || data[t].fullPicture === null || data[t].fullPicture === '') { console.log(`${t} Adding default png`); // Directly assign the property to the object data[t].fullPicture = "https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png"; }
Simplify the Condition (Optional)
If you're okay with treating all "falsy" values (like empty strings, null, undefined, 0, false) as needing the default image, you can shorten the condition to:
if (!data[t].fullPicture) { console.log(`${t} Adding default png`); data[t].fullPicture = "https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png"; }
Note: This will overwrite values like 0 or false if those are valid possible values for fullPicture—stick with the strict check if you need to avoid that.
Handling the Entire Array (Bonus)
If you need to apply this fix to every element in the data array instead of just index t, use a loop like forEach to iterate through all items:
data.forEach((item, index) => { if (!item.fullPicture) { console.log(`${index} Adding default png`); item.fullPicture = "https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png"; } });
Key Takeaways
- Use direct property assignment (
object.property = value) for adding/updating object properties—this is the standard, most efficient way. - Reserve
push()for arrays only; it won't work on objects. - Choose your condition based on whether you need strict checks (only
undefined,null, empty string) or want to cover all falsy values.
内容的提问来源于stack exchange,提问作者turtlepower

