Which is the best way to set an array of n dimensions from a function?
var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];
// only valid for 1-dimension
function set(arr, dim, v) {
arr[dim] = v;
}
set(v1, 2, 33);
Which is the best way to set an array of n dimensions from a function?
var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];
// only valid for 1-dimension
function set(arr, dim, v) {
arr[dim] = v;
}
set(v1, 2, 33);
Your function can't work as designed it needs an index for each dimension
You'd need something like the following http://jsfiddle.net/nZmJT/1/
function setValueInArray(arr, value, index /*, index, index, ... */ ) {
var arrToSet = arr;
for (var i = 2; i < arguments.length - 1; i++) {
arrToSet = arr[arguments[i]];
}
arrToSet[arguments[i]]= value;
return arr;
}
var v1 = [1,2,3];
var v2 = [[1,2],[3,4]];
console.log( setValueInArray(v1, 0, 0) ); // [0,2,3]
console.log( setValueInArray(v2, 0, 0, 0) ); //[[0,2],[3,4]]
Please share with us why you'd like this. I can't think of code that can be generalized to work with multiple dimensions, you usually know the dimension, and just set it like...
v1[2][3] = 'anything';
Since in your case, you wouldn't know how many indexes to pass (otherwise you'd just use bracket access), the following may be a better fit
function setValueInArray(arr, value, indexes) {
var arrToSet = arr;
for (var i = 0; i < indexes.length - 1; i++) {
arrToSet = arr[indexes[i]];
}
arrToSet[indexes[i]] = value;
return arr;
}
Then you can call it passing the array of indexes which is created by some code outside of your control.
setValueInArray(v1, 0, indexes);