3.2 KiB
3.2 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7b7d367417b2b2512b1f | Modify an Array Stored in an Object | 1 | 修改存储在对象中的数组 |
Description
Instructions
user
对象包含三个键。 data
键包含五个键,其中一个键包含一组friends
。从这里,您可以看到灵活的对象如何作为数据结构。我们已经开始编写一个函数addFriend
。完成编写它以便它获取user
对象并将friend
参数的名称添加到存储在user.data.friends
中的数组并返回该数组。 Tests
tests:
- text: <code>user</code>对象具有<code>name</code> , <code>age</code>和<code>data</code>键
testString: 'assert("name" in user && "age" in user && "data" in user, "The <code>user</code> object has <code>name</code>, <code>age</code>, and <code>data</code> keys");'
- text: <code>addFriend</code>函数接受<code>user</code>对象和<code>friend</code>字符串作为参数,并将朋友添加到<code>user</code>对象中的<code>friends</code>数组
testString: 'assert((function() { let L1 = user.data.friends.length; addFriend(user, "Sean"); let L2 = user.data.friends.length; return (L2 === L1 + 1); })(), "The <code>addFriend</code> function accepts a <code>user</code> object and a <code>friend</code> string as arguments and adds the friend to the array of <code>friends</code> in the <code>user</code> object");'
- text: '<code>addFriend(user, "Pete")</code>应该返回<code>["Sam", "Kira", "Tomo", "Pete"]</code>'
testString: 'assert.deepEqual((function() { delete user.data.friends; user.data.friends = ["Sam", "Kira", "Tomo"]; return addFriend(user, "Pete") })(), ["Sam", "Kira", "Tomo", "Pete"], "<code>addFriend(user, "Pete")</code> should return <code>["Sam", "Kira", "Tomo", "Pete"]</code>");'
Challenge Seed
let user = {
name: 'Kenneth',
age: 28,
data: {
username: 'kennethCodesAllDay',
joinDate: 'March 26, 2016',
organization: 'freeCodeCamp',
friends: [
'Sam',
'Kira',
'Tomo'
],
location: {
city: 'San Francisco',
state: 'CA',
country: 'USA'
}
}
};
function addFriend(userObj, friend) {
// change code below this line
// change code above this line
}
console.log(addFriend(user, 'Pete'));
Solution
// solution required