-1

var を作成し、JSON データ (カンマ区切りの値) をそれに渡しましたが、json データを表示したい場合、null しか返されません。コードは次のとおりです。

<script type="text/javascript">
var data1 = [
    {order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];  

document.write(data1);
</script>
4

2 に答える 2

3

次のようにすることもできます。

var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];  

data1.forEach(function(data){
    document.write(data.order);
    document.write(data.country);
    document.write(data.employee);
    document.write(data.customer);
});

または、このようにすることができます

var data1 = [
    {order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];  

$.each(data1[0], function(key, value){
    document.write(key + " " + value); 
});

いずれにせよ、リストにオブジェクトを 1 つだけ格納すると、複数のオブジェクトをループする方法を示さない限り、この回答は少し冗長になります。

var data1 = [
    {order:"145",country:"Dubai",employee:"permanent",customer:"self"},
    {order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];  

data1.forEach(function(data){
    $.each(data, function(key, value){
        document.write(key+" "+value);
    });
});

ここでも jQuery を組み合わせて使用​​していますが、これは最適ではないかもしれませんが、少なくとも、必要なことを達成する方法が複数あることを示すのに役立ちます。

また、配列の forEach() メソッドは MDN で開発されたメソッドであるため、クロスブラウザーに準拠していない可能性があります。

純粋なJSが必要な場合、これは方法の1つです

var data1 = [
    {order:"145",country:"Dubai",employee:"permanent",customer:"self"},
    {order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];  

for(json in data1){
    for(objs in data1[json]){
        document.write(objs + " : " + data1[json][objs]);
    }
}
于 2012-05-29T08:23:07.770 に答える
0

JSON を簡単かつ迅速に印刷するには、以下のようなことができます。ほとんど同じことがオブジェクトにも当てはまります。

 var json = {
        "title" : "something",
        "status" : true,
        "socialMedia": [{
            "facebook": 'http://facebook.com/something'
        }, {
            "twitter": 'http://twitter.com/something'
        }, {
            "flickr": 'http://flickr.com/something'
        }, {
            "youtube": 'http://youtube.com/something'
        }]
    };

画面に出力するには、単純な for in ループで十分ですが、配列を出力せず、代わりに [object Object] を出力してください。答えを簡単にするために、配列のキーと値を画面に表示することについては深く掘り下げません。

これが誰かに役立つことを願っています。乾杯!

for(var i in json) {
    document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
    console.log(i +  ' ' + json[i])
}
于 2016-01-31T21:37:57.540 に答える