当使用JSON.parse实现预期的输出时,我收到错误Unexpected token B in JSON at position 1
。我错过了什么?
var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');
var a =[]; var b = [];
for(var i=0;i<array1.length;i++){
var c = array1[i];
var d = array2[i];
e = "[" + c +","+d +"]";
e =JSON.parse(e);
a.push(e);
}
console.log(a);
&#13;
预期输出
[[ 'BODEBO', '1'],[ 'CARNE','2' ]];
没有json.parse
输出
[ '[BODEBO,1]', '[CARNE,2]' ]
我不想要&#39; &#39;在每个数组元素上
答案 0 :(得分:3)
如果预期的输出具有数组,那么也可以创建一个数组。
var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');
var a = [];
for(var i = 0; i < array1.length; i++){
a.push([array1[i], array2[i]]);
}
console.log(a);
但是当你有地图时谁需要循环?
var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');
console.log(array1.map((s, idx) => [s,array2[idx]]));
答案 1 :(得分:2)
您可以简单地遍历第一个数组,然后将单个数组推送到输出数组。
var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');
var a = [];
for(var i=0;i<array1.length;i++){
a.push([ array1[i], array2[i] ]);
}
// You can now just make use of the 'a' array.
console.log(a);
给你以下输出:[[&#34; BODEBO&#34;,&#34; 1&#34;],[&#34; CARNE&#34;,&#34; 2&#34;]]
答案 2 :(得分:-1)
为了JSON.parse
工作,您需要提供有效的JSON。该函数当前传递的数组如下:
[BODEBO,1]
无效。要使其工作,您需要将每个项目用引号括起来,例如:
["BODEBO","1"]
var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');
var a = [];
var b = [];
for (var i = 0; i < array1.length; i++) {
var c = array1[i];
var d = array2[i];
e = "[\"" + c + "\",\"" + d + "\"]";
e = JSON.parse(e);
a.push(e);
}
console.log(a);
&#13;