最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to printdisplay an array in jquery - Stack Overflow

programmeradmin6浏览0评论

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", ...];

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", ...];
Share Improve this question edited Sep 9, 2015 at 7:34 Lipis 21.8k20 gold badges96 silver badges121 bronze badges asked Sep 9, 2015 at 6:42 DeepakDeepak 1781 gold badge2 silver badges14 bronze badges 5
  • 1 alert(JSON.stringify(arr)) or alert(arr.join(" ")) – Satpal Commented Sep 9, 2015 at 6:43
  • var arr = [1,2,3,4,5,6,7,8,9,10]; alert(arr[1]); – guradio Commented Sep 9, 2015 at 6:43
  • 5 If you're just trying to debug, I would HIGHLY suggest ditching alert and using console.log() – flcoder Commented Sep 9, 2015 at 6:51
  • 1 @flcoder: I'm indeed wondering why console.log() hasn't been suggested from the very beginning. – D4V1D Commented Sep 9, 2015 at 6:54
  • thanks to all... its working but by using this: alert(arr.toString()); alert(arr.join(", ")); .... explain ? – Deepak Commented Sep 9, 2015 at 7:01
Add a ment  | 

7 Answers 7

Reset to default 4

You could also use the JavaScript function toString().

alert(arr.toString());

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 );
})

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.

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

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

console.log(a);

    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);
for(var i = 0; i < teams.length; i++) {
        console.log(teams[i]);
           
}

worked for me.

发布评论

评论列表(0)

  1. 暂无评论