javascript - 在javascript中向对象添加属性

标签 javascript object

function addProperty(object, property) {
  // add the property to the object with a value of null
  // return the object
  // note: the property name is NOT 'property'.  The name is the value of the argument called property (a string)
}

我在一个唯一的家庭作业问题上有点卡住了。我想我明白它要求我做什么。我想传入一个对象并添加一个新属性并将其默认值设置为 null。

这是我尝试做的事情

function addProperty(object, property) {
  // add the property to the object with a value of null
  // return the object
  // note: the property name is NOT 'property'.  The name is the value 
  object.property = property;
  object[property] = null;
  return object;
    }

这似乎没有按照我需要的方式工作,因为我相信该对象应该产生类似的结果

const object = {
propertyPassedIn: null,
};

有人可以帮助我或为我指明正确的方向吗?

最佳答案

这对我有用

function addProperty(object, property) {
  // add the property to the object with a value of null
  // return the object
  // note: the property name is NOT 'property'.  The name is the value 
  // object.property = property;
  object[property] = null;
  return object;
}

var obj = {x:1,y:null};
// undefined
obj
// {x: 1, y: null}
addProperty(obj, 'z');
// {x: 1, y: null, z: null}

关于javascript - 在javascript中向对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49343304/

相关文章:

javascript - Eloquent JS : Chessboard – why is first row misaligned?

c# - 在 C# 中转换对象 (ASP.Net MVC)

javascript - 变量/对象是按值传递的吗?为什么我不能用 JavaScript 中的变量更改对象的属性?

javascript - h5validate 如何要求重复密码

javascript - Angular ng src 无法在 Visual Studio Cordova 中工作

javascript - 如何在 ionic 3 中使用 jquery

python - 如何在 Discord.py 中获取消息的时间戳?

javascript - 如何在 Javascript 中添加/替换嵌套对象中的值(不丢失原始引用)?

javascript - Safari 类型错误 : 'undefined' is not a function (evaluating 'Object.assign(...)' )

php - 我的排序方法有什么问题(AJAX、PHP MySQL)