我正在创建一个功能并坚持这个提示:
updateObject():应该取一个对象,一个键和一个值。应该使用新值更新对象上的属性键。如果在创建它时不存在。
这是我的代码:
function updateObject(object, key, value) {
if (object.key) {
return object.key = value;
} else if (object.key === false) {
return object.key;
}
}
这是它试图通过的测试:
QUnit.test("updateObject() : Should take an object, a key and a value. Should update the property <key> on <object> with new <value>. If <key> does not exist on <object> create it.", function(assert){
var data = {a: "one", b: "two", "hokey": false};
assert.deepEqual(updateObject(data, "b", "three"), {a:"one", b:"three", hokey: false});
var data = {a: "one", b: "two", "hokey": false};
assert.deepEqual(updateObject(data, "ponies", "yes"), {a:"one", b:"two", hokey: false, ponies: "yes"});
var data = {a: "one", b: "two", "hokey": false};
assert.deepEqual(updateObject(data, "a", Infinity), {a:Infinity, b:"two", hokey: false});
});
我做错了什么?
答案 0 :(得分:0)
如果需要使用变量访问对象键,请使用方括号。另外hasOwnProperty
可用于检查对象是否有键
function updateObject(object, key, value) {
if (object.hasOwnProperty(key)) {
return object[key] // will return value of the key in that object
} else {
return object[key]=value; // will create a new key and will assign value
}
}
答案 1 :(得分:0)
您需要从函数中返回更新的对象,以便传递测试。
function updateObject(object, key, value) {
object[key] = value;
return object;
}