从字符串创建JS多维数组 [英] Create a JS multidimensional array from string
问题描述
我想创建一个军事数组,如下所示
I would like to create a miltidimentional array as follows so
var multi-arr = [
["A,2,5"],
["B,4,4"],
["C,4,4"]
]
使用ajax从数据库获取的字符串值.
from string values gotten from the database using ajax.
从数据库获取的字符串数据,以#分隔
string data gotten from db delimited by #
var string = "A,2,5# B,4,4# C,4,4";
我用'#'分隔符分割了字符串
I split the string by a '#' delimiter
arr1=string.split(/\s*\#\s*/g);
在下面创建数组
var arr = ["A,2,5", "B,4,4", "C,4,4"];
我想进一步拆分上述数组中的项目使用逗号,"作为分隔符并创建多维数组
I want to further split the items in the above array using the comma ',' as a delimiter and create a multidimensional array
我的问题是循环仅压入数组的最后一项
My problem is the loop only pushes in the last item in the array
for (i = 0; i < arr.length; i++) {
var arr2 = [];
arr2[i]=arr2.push(arr1[i].split(/\s*\,\s*/g));
}
console.log(arr2);
我在做什么错?还是我能做得更好?
What am i doing wrong? or what can i do better?
推荐答案
var语句应位于for循环的外部,并且您无需进行分配和推送.
The var statement should be outside the for loop and you don't need to do the assignment and the push.
var i;
var string = "A,2,5# B,4,4# C,4,4";
var arr1 = string.split("#");
var arr2 = [];
for (i = 0; i < arr1.length; i++) {
arr2[i]=arr1[i].split(",");
}
console.log(arr2);
如Mike'Pomax'所建议-您可以将服务器中的数据作为JSON返回.如果您使用的是PHP,可以这样进行:
As suggested by Mike 'Pomax' - you could return the data from the server as JSON. If you're using PHP, that can be done like so:
header('Content-Type: application/json');
echo json_encode($queryResult);
exit;
这篇关于从字符串创建JS多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!