Reputation: 2043
Just when I think I'm getting an understanding of the syntax of Javascript, I run into something like this...
I saw this code on the jqPlot plugin page.
what kind of array is [[]]
in javascript? A nested array? I thought I understood the double brackets, but in the commented text, I don't understand why there is an extra set (question below).
$(document).ready(function(){
// Our data renderer function, returns an array of the form:
// [[[x1, sin(x1)], [x2, sin(x2)], ...]]
var sineRenderer = function() {
var data = [[]];
for (var i=0; i<13; i+=0.5) {
data[0].push([i, Math.sin(i)]);
}
return data;
};
Why is there an extra set of brackets in this commented statement (the outermost set)?
[[[x1, sin(x1)], [x2, sin(x2)], ...]]
Thanks
Upvotes: 0
Views: 1548
Reputation: 81
Hunter is correct -- it's the syntax for an array containing other arrays. You could also look at doing this as an object, as illustrated here: http://www.quirksmode.org/js/associative.html.
Upvotes: 1
Reputation: 664464
Yes, it's a nested array. The data
array contains an array to which other arrays with value and sine of the value are pushed.
AFAIK, the jQPlot plugin would use every array in data
to print a new graph. You could for example do
function graph(fn, from, to, gap) {
// creates an array with points
var res = [];
for (var i=from; i<to; i+=gap) {
res.push([i, fn(i)]);
}
return res;
}
var data = [
graph(Math.sin, 0, 13, 0.5),
graph(Math.cos, 0, 13, 1)
];
...
Upvotes: 1
Reputation: 382696
Since you are putting in arrays in your data
array (which creates arrays inside an array), doing this would avoid that:
var data = [];
for (var i=0; i<13; i+=0.5) {
data.push([i, Math.sin(i)]);
}
When you use [[]]
and then do data[0]
, you are not utilizing outer array there which jumps in when you output it.
Upvotes: 1
Reputation: 198314
It would be a single set of brackets if they said data.push
. Since the 0-th element of the array is an array, they use data[0].push
to stuff stuff in it.
Why they need it double-wrapped, no idea without more context.
Upvotes: 1