简体   繁体   English

为什么我无法在Javascript上控制台记录/字符串化整个数组?

[英]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. 所以我很努力地尝试在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. 我得到一个空的Array []或一个空的JSON对象。

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. 我试图实现的是从该数组创建一个复杂的JSON对象。

This is my actual code: For prop1: 这是我的实际代码:对于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): 对于prop2(这实际上在生成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. 我假设您将globalForm创建为数组。 Arrays in JavaScript only understand integer indices. JavaScript中的数组仅理解整数索引。 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. JavaScript中点符号和括号索引的等效性可能会误导您。

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. 还值得注意的是它不是json对象,javascript对象或描述对象的json字符串。

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/ 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 提示:当我遇到问题时,我会尝试在jsfiddle.net或plunker之类的工具中进行小版本的“健全性检查”,希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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