写一个修改唱片集(数组对象)的函数
You are given an object literal representing a part of your musical album collection. Each album has a unique id number as its key and several other properties. Not all albums have complete information.
You start with an updateRecords function that takes an object literal, records, containing the musical album collection, an id, a prop (like artist or tracks), and a value. Complete the function using the rules below to modify the object passed to the function.
- Your function must always return the entire record collection object.
- If
propisn'ttracksandvalueisn't an empty string, update or set that album'sproptovalue. - If
propistracksbut the album doesn't have atracksproperty, create an empty array and addvalueto it. - If
propistracksandvalueisn't an empty string, addvalueto the end of the album's existingtracksarray. - If
valueis an empty string, delete the givenpropproperty from the album.
const 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: [] }, 5439: { albumTitle: 'ABBA Gold' } }; //修改上面唱片集的函数如下: function updateRecords(records, id, prop, value) { if (prop!='tracks' && records[id][prop] !='') { records[id][prop]=value;//注意取对象属性时,对于函数的形参只能用[]来,用.会报错!因为它们只是函数的形参,不是对象的属性!! }; if (prop==='tracks') { if (records[id].hasOwnProperty('tracks')) { records[id][prop].push(value); } else { records[id][prop]=[value]; } }; if (!(value.length>0)) {//此条件也可以写成value==='' delete records[id][prop]; }; return records; } //测试: updateRecords(recordCollection, 5439, 'artist', 'ABBA');

浙公网安备 33010602011771号