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