I have problems with .stringify()
, but I think my JavaScript array must be wrong, here's my code:
var questions = new Array();
$('#Valid').hover(function(){
for (i=0;i < $('.Questions').length;i++){
questions[i]=new Array();
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)
})
The stringJSON var returns :
[[]]
What am I doing wrong?
You must create each multidimensional ARRAY/VARRAY type you need for your applications using a CREATE TYPE (ARRAY form) request. When you create a new multidimensional ARRAY/VARRAY type, you must explicitly specify the lower and upper boundaries for each dimension, as well as the element data type of the array.
While we're converting an object literal into a JSON string in this example, JSON. stringify() also works with arrays.
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.
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);
});
Replace questions[i]=new Array();
with questions[i] = {};
(or = new Object();
if you really want this "ugly" syntax).
Arrays in JavaScript are like arrays in languages like C: They only support integer indexes in the interval [0, array.length)
.
For associative arrays, you use objects which are created using the object literal {}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With