mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-01-04 18:05:32 -05:00
1.7 KiB
1.7 KiB
id, title, challengeType, forumTopicId
| id | title | challengeType | forumTopicId |
|---|---|---|---|
| 587d78b2367417b2b2512b0f | 使用 pop() 和 shift() 从数组中删除项目 | 1 | 301165 |
--description--
push()和unshift()都分别有一个作用基本与之相反的函数:pop()和shift()。你现在或许已经猜到,与插入元素相反,pop()从数组的末尾移除一个元素,而shift()从数组的开头移除一个元素。pop()和shift()与对应的push()和unshift()的关键区别在于,前者不能接受输入参数,而且每次只能修改数组中的一个元素。
让我们来看以下的例子:
let greetings = ['whats up?', 'hello', 'see ya!'];
greetings.pop();
// now equals ['whats up?', 'hello']
greetings.shift();
// now equals ['hello']
还可以用这些方法返回移除的元素,像这样:
let popped = greetings.pop();
// returns 'hello'
// greetings now equals []
--instructions--
我们已经定义了一个popShift函数,它会接收一个数组作为输入参数并返回一个新的数组。请你修改这个函数,使用pop()和shift()来移除输入的数组的第一个元素和最后一个元素,并将这两个被移除的元素赋值给对应的变量,使得返回的数组包含它们的值。
--hints--
popShift(["challenge", "is", "not", "complete"])应返回["challenge", "complete"]
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
'challenge',
'complete'
]);
popShift函数应该使用pop()方法
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
popShift函数应该使用shift()方法
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);