3.0 KiB
3.0 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7da9367417b2b2512b67 | Add Elements to the End of an Array Using concat Instead of push | 1 | 301226 | Добавление элементов в конец массива используя concat вместо push |
Description
concat
как способ объединить массивы, не изменяя исходные. Сравните concat
с методом push
. Push
добавляет элемент в конец того же самого массива, на котором он вызывается, изменяя этот массив. Вот пример: var arr = [1, 2, 3];
arr.push ([4, 5, 6]);
// arr изменяется на [1, 2, 3, [4, 5, 6]]
// Не функциональный способ программирования
Concat
предлагает способ добавления новых элементов в конец массива без каких-либо мутирующих побочных эффектов.
Instructions
nonMutatingPush
чтобы она использовала concat
для добавления newItem
в конец original
вместо push
. Функция должна возвращать массив.
Tests
tests:
- text: Your code should use the <code>concat</code> method.
testString: assert(code.match(/\.concat/g));
- text: Your code should not use the <code>push</code> method.
testString: assert(!code.match(/\.push/g));
- text: The <code>first</code> array should not change.
testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
- text: The <code>second</code> array should not change.
testString: assert(JSON.stringify(second) === JSON.stringify([4, 5]));
- text: <code>nonMutatingPush([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.
testString: assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]));
Challenge Seed
function nonMutatingPush(original, newItem) {
// Add your code below this line
return original.push(newItem);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
Solution
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);