Opposite of push(); [duplicate]

大城市里の小女人 提交于 2019-12-03 03:23:08

问题


I need help on this problem - 'What is the opposite of the JavaScript push(); method?'

Like say I had a array -

var exampleArray = ['remove'];

I want to push(); the word 'keep' -

exampleArray.push('keep');

How do I delete the string 'remove' from the array?


回答1:


Well, you've kind of asked two questions. The opposite of push() (as the question is titled) is pop().

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.pop();
console.log(exampleArray);

pop() will remove the last element from exampleArray and return that element ("hi") but it will not delete the string "myName" from the array because "myName" is not the last element.

What you need is shift() or splice():

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.shift();
console.log(exampleArray);

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.splice(0, 1);
console.log(exampleArray);

For more array methods, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods




回答2:


push() adds at end; pop() deletes from end.

unshift() adds to front; shift() deletes from front.

splice() can do whatever it wants, wherever it wants.



来源:https://stackoverflow.com/questions/25517633/opposite-of-push

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!