Deepak
Deepak

Reputation: 178

How to print/display an array in jquery

I have an array

var arr = [1,2,3,4,5,6,7,8,9,10];

How to display all items of the array using an alert box?

I have tried : alert(arr); and it shows nothing.

Edit: I want display this array like php print_r function.

 output needed like: array["key" => "value", "key" => "value", ...];

Upvotes: 5

Views: 23043

Answers (7)

Merin Antony
Merin Antony

Reputation: 1

for(var i = 0; i < teams.length; i++) {
        console.log(teams[i]);
           
}

worked for me.

Upvotes: -1

webCoder
webCoder

Reputation: 1

    var arr = [1,2,3,4,5,6,7,8,9,10];
    var arrstr="arr[";
    for(var i=0;i<arr.length;i++){
        arrstr+="\""+i+"\" : \""+arr[i]+"\"";   //you can change ":" for "=>", if you like
        if(i!=arr.length-1){//if not the last one ,add "," 
            arrstr+=",";    
        }else{
            arrstr+="]";
        }
    }

    alert(arrstr);

Upvotes: 0

Persijn
Persijn

Reputation: 14990

var a = {
  "1": 15,
  "2": 16,
  "3": 17,
}

console.log(a);

Upvotes: 1

D4V1D
D4V1D

Reputation: 5849

As I'm wondering why console.log() hasn't been provided as an answer, here it is.

Do:

console.log(arr);

And open the developper toolbar (F12 on most browsers) and go to the console tab. You should be able to see and expand your array.

Upvotes: 2

guradio
guradio

Reputation: 15555

var arr = [1,2,3,4,5,6,7,8,9,10];
alert(arr);
for(var i = 0 ; i < arr.length; i++){
alert("key "+ i + " and " + "Value is "+arr[i]);
}

FIDDLE

To alert each value use this

Upvotes: 1

Holonaut
Holonaut

Reputation: 166

You could also use the JavaScript function toString().

alert(arr.toString());

Upvotes: 4

Milind Anantwar
Milind Anantwar

Reputation: 82231

To show them in csv, you can use .join(",") along with array object:

alert(arr.join(", "));

for printing individually:

$.each(arr, function( index, value ) {
  alert( value );
})

Upvotes: 3

Related Questions