2009-10-23 80 views
0
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]'

我有一个巨大的多维数组,我想将它序列化为一个字符串。 up_to_dimension的论点是要求多维数组序列化

该功能必须在Firefox,Opera,Safari和IE的最新版本中运行。表演是关键。

回答

3
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(", ") + "]"; 
} 
1

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(",") + "]"; 
}