在javascript IE中从字符串创建子数组

时间:2013-08-20 09:44:39

标签: javascript 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"

我希望它转换为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中运行?

5 个答案:

答案 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)

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

地图 - MDN

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

答案 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]
    }
 }

http://jsfiddle.net/GvyuV/

中查看