I'm using a 3rd party javascript library which requires a nested array to be passed to a function. I'm using this function several times, and so storing the array in a variable and passing it to the functions. However, part of the string of 1 element of the array needs to be the current id of the thing I'm passing; I've got something that works that looks a bit like:
myArray = [["foo bar id","some data"],["foo2 bar2 id","some other data"]]
func1(($m1 = myArray.slice(0),
$.each($m1, function(i){
$m1[0] = myArray[i][0].replace("id","1");
})))
Is it really necessary to make a copy of the array; is there a way of doing it via the $(this)
object, or would that not work because that's only in the scope of the .each
loop, and doesn't get passed back to func1
?
Update
The original answer below doesn't seem to work - the values of the array the 2nd time I reference it are the values given in the first instance:
myArray = [["foo bar id","some data"],["foo2 bar2 id","some other data"]]
func1(
myArray = myArray.map(function(value)
{
value[0] = value[0].replace(/\bid\b/gi, '1');
console.log(value[0]); //returns "foo bar 1" as expected
return value;
});
)
func1(
myArray = myArray.map(function(value)
{
value[0] = value[0].replace(/\bid\b/gi, '2');
console.log(value[0]); //This returns "foo bar 1", not "foo bar 2"!
return value;
});
)
Update (full proper code!)
To put it all into context, the 3rd party library is jsmol, which allows molecular graphics to be displayed. jsmol includes some convenience functions for simple html elements, the one I'm using is Jmol.jmolMenu() - the nested array I've actually got is
arr = [ ["select model=id; color blue", "colour this model blue"],
["select model=id; color green", "colour this model green"]
]
and then I have n molecular models displayed in the same applet
, which jsmol references as 1.1, 2.1, 3.1, ... etc
I have n Jmol.jmolMenu
s (which just create html select lists); the 1st one to change the colour of 1.1, the second one to change the colour of 2.1 and so on - this is where I need to change the value of the id to the relevant model, and why the replace can only replace the current instance of the current copy - otherwise it makes the lists for the other molecules not work!
In my first menu, I effectively need
Jmol.jmolMenu(jmol,
[
["select model=1.1; color blue", "colour this model blue"],
["select model=1.1; color green", "colour this model green"]
]
);
and in my second:
Jmol.jmolMenu(jmol,
[
["select model=2.1; color blue", "colour this model blue"],
["select model=2.1; color green", "colour this model green"]
]
);
I hope this makes a bit of sense, and explains why I need the arrays modifying when I do (which might have seemed weird before!)