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);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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/
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…
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
Then you can call it passing the array of indexes which is created by some code outside of your control.