如何在数组中打印结构化数组和推送值

时间:2013-01-08 08:19:21

标签: jquery

我是JQuery的新手。我在这里学习JQuery基础知识,并认真了解数组如何在jQuery中工作。

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
    <style>
  div { color:blue; }
  span { color:red; }
</style>
    <script src="jquery-latest.js"></script>
</head>
<body>

<div id="myDiv"></div>

<script>
$(document).ready(function() {

    var testArray = ["test1","test2","test3","test4"];
    var new_array=[];
    var vPool="";

    /*i tried but this pushing code dosen't work*/

   //pushing values in new_array
    $("new_array").push({"test1","test2","test3","test4"});

    //fetching the values of new_array 
    $.each(new_array, function(i, val) {
      vPool+=val + "<br />";
    });
    $('#myDiv').html(vPool);--->
    //vPool="";

    /*But i tried this code it work fine */

    //fetching the values of new_array 
    $.each(testArray, function(i, val) {
      vPool+=val + "<br />";
    });
    $('#myDiv').html(vPool); 
    //vPool="";

});
</script>

</body>
</html>

我想知道如何打印结构化数组,就像我们在PHP中打印一样:

echo "<pre>";
print_r($array);

1 个答案:

答案 0 :(得分:1)

删除$("") arround new_array。您也正在推送定义不正确的对象。 push()函数与jQuery无关,它是纯JavaScript。

关于整个阵列的打印,您应该在已安装Firebug扩展程序的Chrome或Firefox中试用console.log()

$(document).ready(function() {

    var testArray = ["test1","test2","test3","test4"];
    var new_array=[];
    var vPool="";

    /*i tried but this pushing code dosen't work*/

    //pushing values in new_array
    new_array.push("test1","test2","test3","test4");
    console.log(new_array);

    $.each(new_array, function(i, val) {
        vPool+=val + "<br />";
        console.log(val);
    });

});

push()函数返回数组的新长度。