I have to use an array which is statically initialized as:
var my = new Array([30,10],[3,32])
I want to create this array dynamically but it seems it is not possible as it appends quotes and creates like this:
var my = new Array("[30,10],[3,32]")
function(data) {
var my = new Array(data);
}
I have tried replace, substring and any other possible way. Any body have any idea how to do this. This is very urgent.
pimvdb
155k80 gold badges313 silver badges358 bronze badges
asked Mar 19, 2011 at 13:59
Deepak Agarwal
9046 silver badges21 bronze badges
3 Answers 3
Try:
var arr = JSON.parse("[[30,10],[3,32]]");
answered Mar 19, 2011 at 14:04
pimvdb
155k80 gold badges313 silver badges358 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
pimvdb
@T.J. Crowder: Because you can safely convert a String into an Aray this way I guess.
Buhake Sindi
@T.J. Crowder, I wonder the same thing, I don't see the OP ever talking about JSON.
T.J. Crowder
@pimvdb: But my impression was that he wasn't using a string. In fact, he seems to be complaining that something is mysteriously turning his arguments into a string, though I can't imagine what. Anyway, the question is pretty unclear, so your guess is as good as mine. :-)
pimvdb
@T.J. Crowder: Oh I'm sorry, I thought 'dynamically' meant that (instead of hardcoding) a String at runtime is supplied, which has to be converted to an array.
T.J. Crowder
@pimvdb: Could be! I wouldn't think that (there are lots of things you do "dynamically"), but hey... Unless @Deepak bothers to clarify, like I said, your guess is as good as mine. :-)
|
Why not create something like this?
var my = [[30,10],[3,32]];
answered Mar 19, 2011 at 14:04
Buhake Sindi
89.5k30 gold badges176 silver badges234 bronze badges
1 Comment
T.J. Crowder
+1 This would be the preferred notation. But his original, as quoted, should also work (provided nothing's redefined
Array), it doesn't take us into the parts of new Array that are...tricky...you should use JSON.parse or even eval
answered Mar 19, 2011 at 18:27
gion_13
41.5k10 gold badges99 silver badges111 bronze badges
1 Comment
gion_13
i know, but for this example it is suitable. you know what type of js you're evaluating
lang-js
eval?var my = new Array([30,10], [3,32]);is perfectly valid. It creates an array with two entries, each of which is, in turn, an array with two entries: jsbin.com/abemi4 It also works if the values come from other variables (e.g., rather than literals): jsbin.com/abemi4/2 In your quoted function, what woulddatacontain?"[30,10],[3,32]"come from? If you create it, why do you create a string? You can add elements to an array witharr.push().