Incorporating diverse objects in JavaScript through click events

In my Javascript code, I work with two arrays named "array1" and "array2".

Initially, the currentArray is set to array1. However, when the user clicks on a certain button, the currentArray switches to array2, and then back to array1 if clicked again.

This approach allows me to easily access the arrays in my code using pseudocode like:

{currentArray}.getText;
{currentArray}.getText;

I am wondering if it is possible to implement this functionality. If so, how can I achieve it? I am aware that using if statements is one way, but I prefer having the simplicity of just modifying the currentArray variable without scattered if statements throughout the code.

Answer №1

To switch between arrays in your code, create a new variable named "currentArray" and assign it to the desired array.

var currentArray;

currentArray = array2;

If you have a function that is dependent on a specific global variable:

function foo() {
  // do something
  var x = array1[2];
  // ...
}

Even if you alter the contents of "array1", the function will still reference it. In JavaScript, functions remain fixed and cannot be changed to refer to a different array.

Answer №2

Here is what you were looking for.

jsFiddle link

var currentArray,
    arr1 = [1, 2, 3],
    arr2 = [4, 5, 6];

$('button').click(function(e) {
    currentArray = currentArray == arr1 ? arr2 : arr1;
});

Answer №3

If you have an array object in Javascript, feel free to use it to create one. Alternatively, you can utilize any tools that DOM offers.

One way to achieve this is by following this pattern:

var my_array = new Array();
for (var i = 0; i < 10; i++) {
   my_array[i] = source_array[i];
}
var x = my_array[4];

Another method is to simply copy it like this:

my_array = souce_array;

Keep in mind that the second approach will only copy the reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

Jasmine for testing HTTP POST method in a unit test case

I am struggling to write a unit test case for the post method in an Angular service. I keep getting an error saying $http is undefined. Below you can see my code. Can anyone please help me figure out what I am missing? I am adding the module using a separ ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Refresh your jQuery function without the need to reload the entire page

Is there a way to update a function's parameters without reloading the entire page? For instance, if I modify the 'style' dropdown value as shown in the URL image, can it be passed to the accordion function so that the accordion's color ...

Ways to retrieve the baseURL of an axios instance

This question is being posted to provide an easy solution for fellow developers who may be looking for an answer. //Suppose you have an axios instance declared in a module called api.js like this: var axios = require('axios'); var axiosInstance ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

Ways to Increase jQuery Element ID

I have several instances of jPlayer (a jQuery audio player) set up: jPlayer1, jPlayer2, jPlayer3, jPlayer4. Each one is initialized and preloaded with audio files. The following function will loop through an existing array and attach a method to play the ...

Continuously receiving unhandled promise rejection errors despite implementing a try-catch block

Every time I run my code, I encounter the following issue: An UnhandledPromiseRejectionWarning is being thrown, indicating that a promise rejection was not properly handled. This can happen if you throw an error inside an async function without a catch bl ...

Retrieving radio button values in React from a different component

I am dealing with a child component that contains radio buttons, each with its own value. I have imported this child component into a parent component to manage its state from the parent component. With the child component added, I need to access all the i ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

In the Node environment, why does null evaluate as less than 3 while also being greater than 3?

How come null is false when compared to 3 in node, and true when compared to 3? $ node > null > 3 false > null < 3 true ...

Let's update the VUE app's development server to point to my-testing-web-address.com instead of the default localhost:

I am working on a VUE application and I am trying to run it on an external link instead of localhost. I attempted to configure a vue.config.js devServer: { host: 'http://my-testing-web-address.com', port: 8080, ... } and adjusted t ...

I need help figuring out how to get a horizontal scrollbar positioned at the top of a div to function properly once the content has been loaded using ajax

HTML CODE <div id="scrollidout" style="overflow: auto; overflow-y: hidden; "> <div id="scrollidin" style="padding-top: 1px; height: 20px; width: 1000px">&nbsp;</div> </div> <div class="resultcontent" style="overflow ...

Requesting PayPal for an HTTPS transaction

When attempting to call the Express Checkout Paypal API using $http.get(AngularJS), I encountered error 81002(Method Specified is not Supported). However, when I tried calling the API using the search bar in Google Chrome, I was able to retrieve the token ...

Dynamic menu item created using Material UI state management

I am facing a challenge in displaying different menu items based on the gender state. Below are the constant values I am working with. const maleArray = ["A", "B", "C", "D"] const femaleArray = ["E", " ...

Partially translucent electron window

Is there a way in Electron to create a view similar to the finder in macOS, where the sidebar is opaque and the main content is not? https://i.stack.imgur.com/UKXg2.jpg I am aware of how to make an entire window opaque, but I'm unsure if it's p ...

Exploring the potential of $scope within $timeout in AngularJS

I am attempting to display a default message on a textarea using AngularJS. Some of the values I want to include require the use of $timeout to retrieve the values. The message does not appear to show up with the following code: <textarea class="t ...

Tips on creating a literal type that is determined by a specific value within an object

In the flow, I am able to create a dynamic literal type in this manner: const myVar = 'foo' type X = { [typeof myVar]: string } const myX: X = { foo: 1 } // will throw, because number const myX: X = { foo: 'bar' } // will not throw ...

Using jQuery to toggle visibility of various elements without needing specific identifiers

I have coded a HTML and JS snippet for displaying and hiding a div element, which is currently functioning correctly. However, I want to be able to use multiple boxes on a single page and I need a way to determine which box-header was clicked. Is there a ...

What is the best way to deactivate ng-repeat using a button in AngularJS?

How can I disable the apply button once it has been clicked by the user in a list of stores based on services? I am using ng-repeat to display the listing. Additionally, how can I write an apply function to disable a particular service once it has been app ...