Opposite push ();

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

As if I have an array - var exampleArray = ['myName'];

I want push(); the word 'hi' - exampleArray.push('hi');

How to remove the string 'myName' from an array?

+71
javascript arrays push
Aug 27 '14 at 1:35
source share
2 answers

Well, you asked two questions. The opposite of push() (as the question is called) 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 remove the string "myName" from the array, because "myName" is not the last element.

You need 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 additional array methods, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods

+62
Aug 27 '14 at 1:56 on
source share

push() adds to the end; pop() is removed from the end.

unshift() added forward; shift() is removed in front.

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

+73
Aug 27 '14 at 1:38
source share



All Articles