madhu
madhu

Reputation: 1018

how to use the pop() option in array in javascript

I have a list which i'm pushing into an array dataList. now I another function i need to pop the contents how will i go about it. Here is the code which i'm trying.

var dataList = new Array;
function addTheContents(){
// .... I'm doing some ajax call and getting one list,
success : function(map) {
                console.log(map);
                dataList.push(map);
                        },
error :  function() {
                alert("error occured!!!");
            },
}

function getListData(){

 dataList.pop()..... how will i get the contents from the datalist after pushing??

}

Upvotes: 0

Views: 494

Answers (2)

NiiL
NiiL

Reputation: 2827

If you want to print all elements from your datalist you can use this code.

$.each(dataList, function(index, val) {
    console.log(val.category);
});

In this code you will get index as key and val as value at that position.

but pop() is used to remove last element from array like.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();

output:- Banana,Orange,Apple

Upvotes: 0

jfriend00
jfriend00

Reputation: 707238

dataList is an array. You can read the items from the array by iterating over the indexes of the array as in:

for (var i = 0; i < dataList.length; i++) {
    // do something with dataList[i]
}

You can read just the last item in the array:

var item = dataList[dataList.length - 1];
// do something with item here

Or, if you just want to remove and retrieve the last from the array, you can do this:

var item = dataList.pop();
// do something with item here

MDN documentation for .pop() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop. It's basically the opposite of .push().

There are a zillion other operations you can carry out on an array and they are all listed here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array


In your specific code example where you are doing an ajax call, you also need to understand that most ajax calls are asynchronous. That means they finish some time in the future. As such, you can't just call the ajax call and then immediately examine dataList. Instead, you need to put any code that needs to reference dataList in the success handler for the ajax call or you need to call that code from the success handler and then pass dataList to it. This is how asynchronous programming works in javascript.

Upvotes: 3

Related Questions