开发者

Multidimensional array serialization

function source_of (array, up_to_dimension) {

  // Your implementation

}

开发者_运维问答source_of([1, [2, [3]]], 0) == '[1, ?]'
source_of([1, [2, [3]]], 1) == '[1, [2, ?]]'
source_of([1, [2, [3]]], 2) == '[1, [2, [3]]]'

source_of([532, 94, [13, [41, 0]], [], 49], 0) == '[532, 94, ?, ?, 49]'

I have a huge multidimensional array and I want to serialize it to a string. up_to_dimension argument is required.

The function must work at least in latest versions of Firefox, Opera, Safari and IE. The performance is a key here.


function source_of(array, up_to_dimension) {
    if (up_to_dimension < 0) {
        return "?";
    }

    var items = [];

    for (var i in array) {
        if (array[i].constructor == Array) {
            items.push(source_of(array[i], up_to_dimension - 1));
        }
        else {
            items.push(array[i]);
        }
    }

    return "[" + items.join(", ") + "]";
}


something like

function to_source(a, limit) {
    if(!a.sort)
        return a;
    else if(!limit)
        return "?";
    var b = [];
    for(var i in a)
        b.push(to_source(a[i], limit - 1));
    return "[" + b.join(",") + "]";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜