Issues Stringifying a multidimensional array with json.js

前端 未结 3 1060
轮回少年
轮回少年 2021-02-08 04:07

I have problems with .stringify(), but I think my JavaScript array must be wrong, here\'s my code:

var questions = new Array();

$(\'#Valid\').hover         


        
3条回答
  •  清酒与你
    2021-02-08 04:50

    Arrays have integer keys, not strings.

    Use an object instead; objects in JS sort of look like associative arrays:

    var questions = new Array();
    $('#Valid').hover(function(){
        for (var i=0;i < $('.Questions').length;i++){
            questions[i]={};
            questions[i]['numero']=$('.Numero:eq('+i+')').html();
            questions[i]['question']=$('.ItemInput:eq('+i+')').val();
            questions[i]['variable']=$('.VarName:eq('+i+')').val();
        }
    
        var stringJSON=JSON.stringify(questions);
        alert(stringJSON);
    });
    

    Setting questions[i] to {} is the key.

    You can shorten this syntax:

    var questions = new Array();
    $('#Valid').hover(function(){
        for (var i=0;i < $('.Questions').length;i++){
            questions[i] = {
                numero:   $('.Numero:eq('+i+')').html(),
                question: $('.ItemInput:eq('+i+')').val(),
                variable: $('.VarName:eq('+i+')').val()
            };
        }
    
        var stringJSON=JSON.stringify(questions);
        alert(stringJSON);
    });
    

提交回复
热议问题