push()
和unshift()
都有相应的几乎相反的方法: pop()
和shift()
。正如您现在可能已经猜到的那样, pop()
不是添加,而是从数组的末尾删除元素,而shift()
从头开始删除元素。 pop()
和shift()
及其兄弟push()
和unshift()
之间的关键区别在于,两个方法都不接受参数,并且每个方法只允许一次由单个元素修改数组。让我们来看看: 让问候= ['什么事情?','你好','看到你!'];我们还可以使用以下任一方法返回已删除元素的值:
greetings.pop();
//现在等于['whats up?','hello']
greetings.shift();
//现在等于['你好']
let popped = greetings.pop();
//返回'你好'
//问候现在等于[]
popShift
,它将一个数组作为参数并返回一个新数组。使用pop()
和shift()
修改函数,删除参数数组的第一个和最后一个元素,并将删除的元素分配给它们对应的变量,以便返回的数组包含它们的值。 popShift(["challenge", "is", "not", "complete"])
应返回["challenge", "complete"]
'
testString: 'assert.deepEqual(popShift(["challenge", "is", "not", "complete"]), ["challenge", "complete"], "popShift(["challenge", "is", "not", "complete"])
should return ["challenge", "complete"]
");'
- text: popShift
函数应该使用pop()
方法
testString: 'assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1, "The popShift
function should utilize the pop()
method");'
- text: popShift
函数应该使用shift()
方法
testString: 'assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1, "The popShift
function should utilize the shift()
method");'
```