You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中为对象添加属性的作业问题求助

Solution for the 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 property argument, this code will overwrite its existing value to null (which fits the problem's requirement to "add the property" — even if it exists, we set it to null).
  • The problem specifies property is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:25:55