【发布时间】:2016-06-04 02:52:39
【问题描述】:
我正在为一门编程课做一个挑战,但由于某种原因,我的代码无法运行。我得到了以下信息:
// 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
我应该满足以下条件:
- updateRecords(5439, "artist", "ABBA") 后,artist 应该是 "ABBA"
- 在 updateRecords(5439, "tracks", "Take a Chance on Me") 之后,曲目的最后一个元素应该是“Take a Chance on Me”。
- updateRecords(2548, "artist", "") 后,不应设置艺术家
- 在 updateRecords(1245, "tracks", "Addicted to Love") 之后,曲目的最后一个元素应该是“Addicted to Love”。
- updateRecords(2548, "tracks", "") 后,不应设置轨道
我的代码仅满足第一个和第四个要求。运行updateRecords(5439, "tracks", "Take a Chance on Me"); 或updateRecords(2548, "tracks", ""); 时,我得到TypeError: Cannot read property 'push' of undefined。当我运行updateRecords(2548, "artist", ""); 时,我得到TypeError: Cannor convert undefined or null to object。
我的代码如下所示:
// Only change code below this line
function updateRecords(id, prop, value) {
if (value !== "" && prop !== "tracks"){
collection[id][prop] = value;
}
else if (value !== "" && prop == "tracks"){
var currentAlbumTracks = collection[id].tracks;
currentAlbumTracks.push(value);
}
else if (value === ""){
delete collection.id.prop;
}
return collection;
}
知道发生了什么吗?
编辑:我已经稍微修改了我的代码。现在我有:
function updateRecords(id, prop, value) {
var currentAlbumTracks = collection[id].tracks;
if (value !== "") {
if (prop !== "tracks"){
collection[id][prop] = value;
}
else if (prop == "tracks"){
if (currentAlbumTracks) {
currentAlbumTracks.push(value);
}
else if (currentAlbumTracks === ""){
collection[id].tracks = [value];
}
}
}
return collection;
}
【问题讨论】:
标签: javascript arrays