Using Javascript, I have two arrays called "array1" and "array2".
I set currentArrray to be array1. Later when user clicks on some button, currentArray switches to Array2 and back to array1 if I click开发者_Go百科 on it again.
This way, whenever there is any part of the code that needs to use an array, I just use something like in pseudocode:
{currentArray}.getText;
{currentArray}.getText;
Is it possible to do something like this? If so, how? I know you can use if statement, but because currentArray is used in different parts of code, it would be nice if I had a simple way like this where all I have to modify is currentArray variable so I dont have if statements scattered all over the place checking what currentArray is.
You can create a variable called "currentArray" and just set it to refer to whatever other array you want.
var currentArray;
currentArray = array2;
If you've got some function that refers to a particular global variable:
function foo() {
// something something
var x = array1[2];
// ...
}
Then it's going to refer to "array1" no matter what. You can change the value of "array1" of course, but you can't make that function refer to "array2" any other way. Functions in JavaScript are immutable.
I believe this is what you are asking for.
jsFiddle
var currentArray,
arr1 = [1, 2, 3],
arr2 = [4, 5, 6];
$('button').click(function(e) {
currentArray = currentArray == arr1 ? arr2 : arr1;
});
You have array object provided in Javascript. You may use it if you want to create one. Else use anything that DOM provides.
You may have to do something like this.
var my_array = new Array();
for (var i = 0; i < 10; i++) {
my_array[i] = source_array[i];
}
var x = my_array[4];
It is also possible to copy simply,
my_array = souce_array;
However this would simply copy the reference.
精彩评论