简体   繁体   中英

Why can't I console log/stringify a whole array on Javascript?

so I am struggling trying to access a -somewhat- complex Array on Javascript.

On a simple way, I have an array like so:

globalForm['prop1'] = anotherArray[];
globalForm['prop2'] = yetAnotherArray[];

If I try to:

console.log(globalForm);
//-or-
JSON.stringify(globalForm)

I get an empty Array [] or an empty JSON object.

But if I do this:

console.log(globalForm['prop1']);
//-or-
JSON.stringify(globalForm['prop1'])

I actually get its contents.

Am I doing something wrong/stupid at trying to log or stringify the whole array? What I am trying to achieve is to create a complex JSON object from that array.

This is my actual code: For prop1:

var completedWeights = [];
globalForm['CompletedFormPhoto'] = images;

var radio_groups = {}
$(".weightRadio:radio").each(function(){
    radio_groups[this.name] = true;
});
for(group in radio_groups){
    thisGroup = $(".weightRadio:radio[name="+group+"]:checked");
    if_checked = !!thisGroup.length;
    completedWeights.push({'IdWeight':thisGroup.attr('name'), 'Value':thisGroup.val()});
}
globalForm['CompletedFormWeight'] = completedWeights;

For prop2 (this actually executes before generating prop1):

var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');


fileInput.addEventListener('change', function(e) {
    var idImg = Date.now();
    var currentImageObj =[];
    var file = fileInput.files[0];
    var imageType = /image.*/;
    var addedImage = document.createElement('div');
    addedImage.className = 'addedImage';

    if (file.type.match(imageType)) {
        var reader = new FileReader();

        reader.onload = function(e) {
            var img = new Image();
            img.src = reader.result;
            img.id = idImg;
            addedImage.appendChild(img);

            var ind = img.src.indexOf(',/9j/') + 5;
            currentImageObj["Photo"] = img.src.substr(ind);

            images[idImg] = currentImageObj;
        }
        reader.readAsDataURL(file); 
        console.log(images);
    } else {
        addedImage.innerHTML = "File not supported!";
    }
    addComment = document.createElement('a');
    addComment.className = "btn btn-default btn-block addComment";
    addComment.setAttribute("data-toggle", "modal");
    addComment.setAttribute("data-target", "#myModal");
    addComment.text = "Agregar Comentario";
    addComment.id = idImg;

    addedImage.appendChild(addComment);
    fileDisplayArea.appendChild(addedImage);
});

Some examples of the actual content of the arrays: 在此处输入图片说明在此处输入图片说明

Thanks in advance.

I assume that you create globalForm as an Array. Arrays in JavaScript only understand integer indices. Since they are still objects, you can of course give them named properties, but those won't fill the array. The equivalence of dot-notation and bracket indexing in JavaScript might have misled you there.

So either you use just numbers like this:

globalForm=[]
globalForm[1]=["whatever"]
globalForm[2]=["etc"]

console.log(globalForm)
=> [undefined, ["whatever"], ["etc"]]

(note that array indices are zero-based)

… Or if you're looking for something more like a mapping between names and values, you should simply use a (non-Array) object:

globalForm={}
globalForm["prop1"]=["whatever"]
globalForm["prop2"]=["etc"]

console.log(globalForm)
=> {prop1: ["whatever"], prop2:["etc"]}

What you are trying to do is perfectly fine there is no reason to stringify complex object

Also worth noting its not a json object, its a javascript object, or a json string that describe an object.

Take a look at this:

var object = {
    prop1 : 'what ever',
    prop2 : 'whatever to',
    prop3 : [
        {a : "a", b: 'b' },
        {a : "a", b: [
            {a : "a", b: 'b' },
            {a : "a", b: "b" },
            {a : "a", b: 'b' }
        ]},
        {a : "a", b: 'b' }
        ]
};

console.log(JSON.stringify(object));
// outPuts : {"prop1":"what ever","prop2":"whatever to","prop3":[{"a":"a","b":"b"},{"a":"a","b":[{"a":"a","b":"b"},{"a":"a","b":"b"},{"a":"a","b":"b"}]},{"a":"a","b":"b"}]}

http://jsfiddle.net/or6gj92y/

Tip: when i run into something i have an issue with i would try a small version of it in something like jsfiddle.net or plunker for a "sanity check" hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM