function append (array, value, dimension) { switch (dimension) { case 0: array.push( value ); break; case 1: array[array.length-1].push( value ); break; case 2: array[array.length-1][array[array.length-1].length-1].push( value ); break; case 3: array[array.length-1][array[array.length-1].length-1][array[array[array.length-1].length-1].length-1].push( value ); break; } return array; } append([0,1], 9, 0) // [0,1,9] append([0,[1]], 9, 0) // [0,[1],9] append([0,[1]], 9, 1) // [0,[1,9]] append([1,[2,[3,[4]]]], 9, 3) // [1,[2,[3,[4,9]]]] append([1,[2,[3],2,[4]]], 9, 2) // [1,[2,[3],2,[4,9]]]
This function works right only if dimension ≤ 3. Also, it is very ugly. What a proper way to do it?
开发者_开发知识库UPDATE:
I know how to recursively get last element of array:function get_last(array, dimension) { return dimension === 0 ? array[array.length-1] : get_last(array[array.length-1], dimension-1); }
I need append.
A recursive algorithm will follow along these lines:
Base Case: Append to 0th dimension, Just do it.
Recursive Case: Append to nth dimension where n > 0, Append to n-1 dimension
Along the way you have to ensure that the values accepted by your function are sensible.
UPDATE: You can try this:
function append2(array, value, dimension){
if(dimension == 0){
array.push( value );
}else{
append(array[array.length-1], value, dimension - 1);
}
return array;
}
This has not been exhaustively tested so be careful.
Array.prototype.append = function (aElem, aDim) {
if (aDim > 0) {
this[this.length - 1].append(aElem, aDim - 1);
} else {
this.push(aElem);
}
return this;
}
then
a = [0,[1,2]]; a.append(9, 0) // [0,[1,2],9]
a = [0,[1,2]]; a.append(9, 1) // [0,[1,2,9]]
a = [1,[2,[3,[4]]]]; a.append(9, 3) // [1,[2,[3,[4,9]]]]
...
(tested under rhino)
Try this iterative algorithm:
function append(array, value, level) {
var tmp = array;
while (level > 0) {
for (var i=tmp.length; i>=0; --i) {
if (tmp[i] instanceof Array) {
tmp = tmp[i];
level--;
break;
}
}
if (i < 0) {
break;
}
}
tmp.push(value);
return array;
}
from my understanding, you always append to the last and deepest array. If yes, there's no need to provide a dimension explicitly
lastArray = function(a) {
var p = a[a.length - 1];
return p.push ? lastArray(p) : a;
}
r = [1, 2, [3, [4, 5]]]
lastArray(r).push(9)
console.log(r) // [1, 2, [3, [4, 5, 9]]]
精彩评论