4.1 KiB
4.1 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7b7d367417b2b2512b1f | Modify an Array Stored in an Object | 1 | 301163 | Измените массив, хранящийся в объекте |
Description
Instructions
user
объект содержит три ключа. Ключ data
содержит пять ключей, один из которых содержит массив friends
. Из этого вы можете видеть, как гибкие объекты являются структурами данных. Мы начали писать функцию addFriend
. Закончите запись, чтобы он взял объект user
и добавил имя аргумента friend
в массив, хранящийся в user.data.friends
и возвращает этот массив.
Tests
tests:
- text: The <code>user</code> object has <code>name</code>, <code>age</code>, and <code>data</code> keys
testString: assert('name' in user && 'age' in user && 'data' in user);
- text: 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
testString: assert((function() { let L1 = user.data.friends.length; addFriend(user, 'Sean'); let L2 = user.data.friends.length; return (L2 === L1 + 1); })());
- text: <code>addFriend(user, "Pete")</code> should return <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']);
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
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) {
userObj.data.friends.push(friend);
return userObj.data.friends;
}