说明:
编写一个带有id,属性(prop)和值的函数。 对于集合中的给定id:如果value为非空(value!=="") 并且道具不是"轨道"然后更新或设置道具的值。如果 道具是"轨道"并且值是非空白的,将值推到 轨道数组的结尾。如果值为空,请删除该道具。总是 返回整个集合对象。
正在运作的代码:
function update(id, prop, value) {
if (prop === "tracks" && value !== "") {
collection[id][prop].push(value);
} else if (value !== "") {
collection[id][prop] = value;
} else {
delete collection[id][prop];
}
return collection;
}
我的代码无效:
function update(id, prop, value) {
if (value !== "" && prop !== "tracks") {
collection[id][prop] = value;
} else if (value !== "" && prop === "tracks") {
collection[id][prop].push(value);
} else if(value === "") {
delete collection[id][prop];
} else {
return collection;
}
}
整个代码:
// Setup
var collection = {
2548 : {
album : "Slippery When Wet",
artist : "Bon Jovi",
tracks : [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468 : {
album : "1999",
artist : "Prince",
tracks : [
"1999",
"Little Red Corvette"
]
},
1245 : {
artist : "Robert Palmer",
tracks : [ ]
},
5439: {
album : "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function update(id, prop, value) {
if (prop === "tracks" && value !== "") {
collection[id][prop].push(value);
} else if (value !== ""){
collection[id][prop] = value;
} else {
delete collection[id][prop];
}
return collection;
}
// Alter values below to test your code
update(5439, "artist", "ABBA");
我遵循了所有指示。但为什么我的代码没有工作呢?为什么另一个正在工作?
答案 0 :(得分:0)
指示说:
始终返回整个集合对象。
然而,如果其他两个陈述都不属实,那么你只返回它......这绝不是!
所以,你需要改变......
function update(id, prop, value) {
if (value !== "" && prop !== "tracks") {
collection[id][prop] = value;
} else if (value !== "" && prop === "tracks") {
collection[id][prop].push(value);
} else if(value === "") {
delete collection[id][prop];
} else {
return collection;
}
}
......进入......
function update(id, prop, value) {
if (value !== "" && prop !== "tracks") {
collection[id][prop] = value;
} else if (value !== "" && prop === "tracks") {
collection[id][prop].push(value);
} else if(value === "") {
delete collection[id][prop];
}
return collection;
}
实现完全相同效果的更好方法是:
function update(id, prop, value) {
if (value === "") {
delete collection[id][prop];
} else if (prop === "tracks") {
collection[id][prop].push(value);
} else {
collection[id][prop] = value;
}
return collection;
}
答案 1 :(得分:0)
我有同样的问题,我创建一个空数组的属性,然后使用.push()来附加值。和Voilá。这是我的代码:
function updateRecords(id, prop, value) {
if (prop !== "tracks" && value !== "") {
collection[id][prop] = value;
} else if (prop === "tracks" && value !== "") {
if(!collection[id].hasOwnProperty(prop)) {
collection[id][prop] = []; //Create a property with empty array
collection[id][prop].push(value); //Append a value into the array
} else {
collection[id][prop].push(value); //Append a value into the exist property array
}
} else if (value === "") {
delete collection[id][prop];
}
return collection;
}