我似乎无法正确地将语法正确添加到专辑ID 5439的值为“ABBA”的新“艺术家”字段,我不断收到未定义“艺术家”的错误,这是有道理但无论哪个我正确的插入方式我似乎错了。
代码用于检查值是否为track并为空,然后使用value变量中的值添加传入的新属性变量。我想用JSON你可以用obj.prop =“value”添加;但这似乎没有用
// 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 updateRecords(id, prop, value) {
if(prop !== "tracks" && value !== null){
collection.id[prop] = prop[value];
}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
答案 0 :(得分:2)
您收到的错误是:
VM5865:33未捕获的TypeError:无法设置
'artist'
的属性undefined
这意味着collection.id
为undefined
。这是有道理的,因为collection
没有id
属性。
您还设置了错误的value
。
替换:
collection.id[prop] = prop[value];
使用:
collection[id][prop] = value;
collection[id]
是您需要的集合。 [prop]
用于定位集合的"artist"
属性。 value
是您要存储为"artist"
的值。
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 updateRecords(id, prop, value) {
if (prop !== "tracks" && value !== null) {
collection[id][prop] = value;
}
return collection;
}
// Alter values below to test your code
var result = updateRecords(5439, "artist", "ABBA");
console.log(result['5439'])
答案 1 :(得分:0)
collection.id[prop] = prop[value];
Collection没有名为id
的属性。 id是直接收集对象的属性。
collection[id][prop] = prop[value];