[英]Question about Record Collection challange from FreeCodeCamp
Why do I have to add square brackets to make this code work?为什么我必须添加方括号才能使此代码正常工作? (eg: records[id][prop] = [value] ; at below) If I take square brackets away, it cannot fulfill the " After updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me"), tracks should have the string Take a Chance on Me as the last element."
(例如:records[id][prop] = [value] ; at below)如果我去掉方括号,它就不能满足“在 updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me") 之后,曲目应该将字符串 Take a Chance on Me 作为最后一个元素。” requirement.
要求。
Why?为什么?
var recordCollection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',
tracks: ['Let It Rock', 'You Give Love a Bad Name']
},
2468: {
albumTitle: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
1245: {
artist: 'Robert Palmer',
tracks: null
},
5439: {
albumTitle: 'ABBA Gold'
}
};
// Only change code below this line
function updateRecords(records, id, prop, value) {
if (prop !== 'tracks' && value !== "") {
records[id][prop] = value;
} else if (prop === "tracks" && records[id].hasOwnProperty("tracks") === false) {
records[id][prop] = [value];
} else if (prop === "tracks" && value !== "") {
records[id][prop].push(value);
} else if (value === "") {
delete records[id][prop];
}
return records;
}
updateRecords(recordCollection, 5439, 'artist', 'ABBA');
tracks
props is an array, as defined for Bon Jovi & Prince : tracks
props 是一个数组,为Bon Jovi & Prince定义:
tracks: ["1999", "Little Red Corvette"]
In this statement, you want to add a tracks
to the artist:在此语句中,您要向艺术家添加
tracks
:
prop === "tracks"
. prop === "tracks"
。
But the artist hasn't any tracks
yet: records[id].hasOwnProperty(“tracks”) === false
.但是艺术家还没有任何
tracks
: records[id].hasOwnProperty(“tracks”) === false
。
So you need to init the tracks
array before adding any values to it:因此,您需要在向它添加任何值之前初始化
tracks
数组:
records[id][prop] = [value];
PS: PS:
You used records[id].hasOwnProperty("tracks") === false
.您使用
records[id].hasOwnProperty("tracks") === false
。 But for Robert Palmer , the props tracks
exists and isn't an array.但是对于Robert Palmer来说,道具
tracks
是存在的,而不是一个数组。
You should use:你应该使用:
(records[id].hasOwnProperty("tracks") === false ||.Array.isArray(records[id]['tracks]))
. (records[id].hasOwnProperty("tracks") === false ||.Array.isArray(records[id]['tracks]))
。
this question is similar to the one from freeCodecamp you have been where you have been instructed to create an empty array and add value to it.这个问题类似于 freeCodecamp 中的问题,您被指示创建一个空数组并为其添加值。 since a new array can be created in this way records[id][prop] = [];
因为可以通过这种方式创建一个新数组 records[id][prop] = []; hence adding a value to the array created will result in: records[id][prop] = [value];
因此向创建的数组添加一个值将导致:records[id][prop] = [value];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.