Issues Stringifying a multidimensional array with json.js

前端 未结 3 1077
轮回少年
轮回少年 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 05:04

    First, your "questions" variable appears to be intended as a real array. What you're putting inside the array, however, are not real arrays — they're just objects with properties.

    var questions = [];
    
    $('#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)
    });
    

    (Note that I also added a var for the "i" loop variable - important!)

    Now, as to why the thing is coming up empty, well, I suspect it's because $('.Questions') is coming up empty.

    Oh and also, this is something you could use the jQuery ".map()" API for:

     $('#Valid').hover(function() {
       questions = $('.Questions').map(function(i, q) {
         return {
           'numero': $('.Numero:eq('+i+')').html(),
           'question': $('.ItemInput:eq('+i+')').val(),
           'variable': $('.VarName:eq('+i+')').val()
         };
       }).get();
    
       var stringJSON = JSON.stringify(questions);
       alert(stringJSON);
    });
    

    That's a little nicer because it gets around the ugly problem of re-evaluating $('.Questions') on every iteration of the loop.

提交回复
热议问题