JavaScript中为对象添加属性的作业问题求助
addProperty Function No worries, this is a super common gotcha when working with dynamic property names in JavaScript! Let's break this down step by step:
The critical detail here is that the property you're adding isn't the literal string "property" — it's the actual value of the property argument (which is a string). That means you can't use dot notation (like object.property = null) because dot notation only works with fixed, hardcoded property names.
Instead, you need to use bracket notation to handle dynamic property names. Here's the correct implementation:
function addProperty(object, property) { // Use bracket notation to assign the dynamic property a value of null object[property] = null; // Return the modified object as required return object; }
Example to Test It Out:
If you call the function like this:
const result = addProperty({}, 'userEmail');
You'll get back { userEmail: null } — exactly what the problem asks for.
Quick Heads-Up:
- If the input object already has a property with the same name as the
propertyargument, this code will overwrite its existing value tonull(which fits the problem's requirement to "add the property" — even if it exists, we set it to null). - The problem specifies
propertyis a string, so we don't need extra validation here, but in real-world code you might want to add checks for valid property names.
内容的提问来源于stack exchange,提问作者user2785628

