2.9 KiB
2.9 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d78b2367417b2b2512b0f | Remove Items from an Array with pop() and shift() | 1 | 使用pop()和shift()从数组中删除项 |
Description
push()
和unshift()
都有相应的几乎相反的方法: pop()
和shift()
。正如您现在可能已经猜到的那样, pop()
不是添加,而是从数组的末尾删除元素,而shift()
从头开始删除元素。 pop()
和shift()
及其兄弟push()
和unshift()
之间的关键区别在于,两个方法都不接受参数,并且每个方法只允许一次由单个元素修改数组。让我们来看看: 让问候= ['什么事情?','你好','看到你!'];我们还可以使用以下任一方法返回已删除元素的值:
greetings.pop();
//现在等于['whats up?','hello']
greetings.shift();
//现在等于['你好']
let popped = greetings.pop();
//返回'你好'
//问候现在等于[]
Instructions
popShift
,它将一个数组作为参数并返回一个新数组。使用pop()
和shift()
修改函数,删除参数数组的第一个和最后一个元素,并将删除的元素分配给它们对应的变量,以便返回的数组包含它们的值。 Tests
tests:
- text: '<code>popShift(["challenge", "is", "not", "complete"])</code>应返回<code>["challenge", "complete"]</code>'
testString: 'assert.deepEqual(popShift(["challenge", "is", "not", "complete"]), ["challenge", "complete"], "<code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>");'
- text: <code>popShift</code>函数应该使用<code>pop()</code>方法
testString: 'assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1, "The <code>popShift</code> function should utilize the <code>pop()</code> method");'
- text: <code>popShift</code>函数应该使用<code>shift()</code>方法
testString: 'assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1, "The <code>popShift</code> function should utilize the <code>shift()</code> method");'
Challenge Seed
function popShift(arr) {
let popped; // change this line
let shifted; // change this line
return [shifted, popped];
}
// do not change code below this line
console.log(popShift(['challenge', 'is', 'not', 'complete']));
Solution
// solution required