1

I have string like

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"

I want it to convert to 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));

Which give me perfect output

[{"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]}] 

But it throws error in IE because of .map function i used . how can i make it work in IE by achieving same result ?

4

5 回答 5

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));
于 2013-08-20T09:46:41.657 回答
2

在这里查看解决方案所有数组功能在 IE 中的精彩答案。在你的代码上面写

 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 .. }
于 2013-08-20T09:50:03.607 回答
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]
    }
 }

在http://jsfiddle.net/GvyuV/中检查它

于 2013-08-20T09:57:16.557 回答
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));
于 2013-08-20T09:48:41.213 回答
1

IE不支持 map()。检查 MDN(Mozilla 开发者网络):

地图 - MDN

看起来 IE 在版本 9 中添加了对 map() 的支持。

于 2013-08-20T09:49:48.223 回答