我有像
这样的字符串var sHTMLTable = "> 24 Hrs.,2,19,20,10,27,16,26,64,246,1|> 12 Hrs.,0,0,0,0,0,0,0,0,0,0|> 8 Hrs.,0,0,0,0,0,0,0,0,0,0|> 4 Hrs.,0,0,0,0,0,0,0,0,0,0|Total,2,19,20,10,27,16,26,64,246,1"
我希望它转换为Sub Array
var res = sHTMLTable.split("|").map(function (s) {
var arr = s.split(",");
return { name: arr.shift(), data: arr.map(Number) };
});
console.log(JSON.stringify(res));
这给了我完美的输出
[{"name":"> 24 Hrs.","data":[2,19,20,10,27,16,26,64,246,1]},{"name":"> 12 Hrs.","data":[0,0,0,0,0,0,0,0,0,0]},{"name":"> 8 Hrs.","data":[0,0,0,0,0,0,0,0,0,0]},{"name":"> 4 Hrs.","data":[0,0,0,0,0,0,0,0,0,0]},{"name":"Total","data":[2,19,20,10,27,16,26,64,246,1]}]
但由于我使用的.map
功能,它在IE中引发错误。 如何通过实现相同的结果使其在IE中运行?
答案 0 :(得分:2)
使用$.map(),因为您使用的是jQuery
var sHTMLTable = "> 24 Hrs.,2,19,20,10,27,16,26,64,246,1|> 12 Hrs.,0,0,0,0,0,0,0,0,0,0|> 8 Hrs.,0,0,0,0,0,0,0,0,0,0|> 4 Hrs.,0,0,0,0,0,0,0,0,0,0|Total,2,19,20,10,27,16,26,64,246,1"
var res = $.map(sHTMLTable.split("|"), function (s) {
var arr = s.split(",");
return { name: arr.shift(), data: $.map(arr, Number) };
});
console.log(JSON.stringify(res));
答案 1 :(得分:2)
在IE here中查看所有数组函数解决方案的精彩答案。 在你的代码上面写
if (!('map' in Array.prototype)) {
Array.prototype.map= function(mapper, that /*opt*/) {
var other= new Array(this.length);
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
other[i]= mapper.call(that, this[i], i, this);
return other;
};
}
或者只是像这样使用jQuery.map
jQuery.map(a, function( ) { //what ever you want todo .. }
答案 2 :(得分:1)
只需将这两个地方的Array.prototype.map
替换为$.map
:
var sHTMLTable = "> 24 Hrs.,2,19,20,10,27,16,26,64,246,1|> 12 Hrs.,0,0,0,0,0,0,0,0,0,0|> 8 Hrs.,0,0,0,0,0,0,0,0,0,0|> 4 Hrs.,0,0,0,0,0,0,0,0,0,0|Total,2,19,20,10,27,16,26,64,246,1"
var res = $.map(sHTMLTable.split("|"), function (s) {
var arr = s.split(",");
return { name: arr.shift(), data: $.map(arr, (Number)) };
});
console.log(JSON.stringify(res));
答案 3 :(得分:1)
答案 4 :(得分:1)
这是我的版本
sHTMLTable = sHTMLTable.split('|');
for(var i = 0, l = sHTMLTable.length; i < l ; i++){
temp = sHTMLTable[i].replace(',','_').split('_');
sHTMLTable[i] = {
name : temp[0],
data : temp[1]
}
}
中查看