So as the title says, I'm trying to set an array from a string variable.
/*** THIS DOES NOT WORK ***/
var Multi = [];
var test = "[0,1],[1,5],[2,3],[3,10]";
Multi.push(test);
/*** THIS WORKS ***/
var Multi = [];
Multi.push([0,1],[1,5],[2,3],[3,10]);
Why is it that when I save it as a string it doesn't work? I need for it to work in a string as I'm pulling these values from another PHP file via AJAX.
Thanks.
You can convert your string to valid JSON by adding [
to the front and ]
to the back, and then use JSON.parse()
to convert your JSON string to an array. Now that you have an array from you string you can extend the Multi
array using Multi.push.apply(Multi, array)
as shown below:
var Multi = [];
var test = "[0,1],[1,5],[2,3],[3,10]";
Multi.push.apply(Multi, JSON.parse('[' + test + ']'));
As mentioned in comments, a cleaner approach would be to make sure that your PHP file generates valid JSON. All of this answer would be the same except that you wouldn't need to manually add the square brackets.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments