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/