2.8 KiB
2.8 KiB
id, challengeType, forumTopicId, localeTitle
id | challengeType | forumTopicId | localeTitle |
---|---|---|---|
587d78b2367417b2b2512b0e | 1 | 301151 | 使用 push() 和 unshift() 添加项目到数组中 |
Description
Array.push()
和Array.unshift()
。
这两个方法都接收一个或多个元素作为参数;对一个数组调用这两个方法都可以将输入的元素插入到该数组中;push()
方法将元素插入到一个数组的末尾,而unshift()
方法将元素插入到一个数组的开头。请看以下例子:
let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];
romanNumerals.unshift('XIX', 'XX');
// 数组现在为 ['XIX', 'XX', 'XXI', 'XXII']
romanNumerals.push(twentyThree);
// 数组现在为 ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']
注意,我们还可以输入变量,这允许我们很灵活地动态改变我们数组中的数据。
Instructions
mixedNumbers
函数,它会接受一个数组作为参数。请你修改这个函数,使用push()
和unshift()
来将'I', 2, 'three'
插入到数组的开头,将7, 'VIII', 9
插入到数组的末尾,使得这个函数返回一个依次包含 1-9 的数组。
Tests
tests:
- text: '<code>mixedNumbers(["IV", 5, "six"])</code>现在应该返回<code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code>'
testString: assert.deepEqual(mixedNumbers(['IV', 5, 'six']), ['I', 2, 'three', 'IV', 5, 'six', 7, 'VIII', 9]);
- text: <code>mixedNumbers</code>函数应该使用<code>push()</code>方法
testString: assert(mixedNumbers.toString().match(/\.push/));
- text: <code>mixedNumbers</code>函数应该使用<code>unshift()</code>方法
testString: assert(mixedNumbers.toString().match(/\.unshift/));
Challenge Seed
function mixedNumbers(arr) {
// change code below this line
// change code above this line
return arr;
}
// do not change code below this line
console.log(mixedNumbers(['IV', 5, 'six']));
Solution
function mixedNumbers(arr) {
// change code below this line
arr.push(7,'VIII',9);
arr.unshift('I',2,'three');
// change code above this line
return arr;
}