Is it better to pass or store arrays by reference?

I am new to the world of javascript and recently downloaded code for an autocompleter feature in search boxes, but unfortunately, it's not functioning as I had hoped. The code snippet that I acquired is below:

Autocompleter.Local = new Class({

    Extends: Autocompleter,

    initialize: function (element, tokens, options) {
        this.parent(element, options);
        console.log(tokens); // Added this line
        this.tokens = tokens;
    },

    query: function () {
        console.log(this.tokens); // Also added this line
        this.update(this.filter());
    }

});

To utilize this code, I carry out the following steps:

var Activities = ['aa', 'bb', 'cc', 'abcd'];

function InitializePage() {

    new Autocompleter.Local('txtSearch', Activities, {
        'minLength': 1,
        'overflow': false,
        'selectMode': 'type-ahead'
    });
}

window.addEvent('domready', function () {
   InitializePage();
});

The tokens parameter within the initialize function represents an array containing all the possible suggestions for the autocompleter. The filter() function sifts through these suggestions to display only relevant ones to the user. My objective is to modify the tokens array periodically so that different suggestions are presented to the user.

In attempting to achieve this, I utilized the following code:

new Request.JSON({ method: 'get', url: 'handler/GetActivities.ashx', autoCancel: true, urlEncoded: false, secure: false,
    headers: { "Content-type": "application/json" },
    onSuccess: function (_json, _jsonText) {
        Activities = _json;
    }
}).send();

After confirming that the Activities variable was indeed updated by this request, I noticed that the tokens variable inside the autocompleter class continued to hold the original initialized array. My question now is how do I ensure that the tokens variable reflects the same data as the activities variable?

Answer №1

The issue lies in the fact that you are overwriting the array instead of replacing its elements. To properly replace elements, you can perform in-place addition and removal using the splice [MDN] method:

Activities.splice(0, Activities.length, _json[0], _json[1], ...);

This code snippet removes all elements (from index 0 to Activities.length) and inserts each element from the _json array.

However, since the number of elements in _json may vary, hardcoding them as shown above is not a good practice. Thankfully, we can utilize the apply [MDN] method to invoke a function with a variable number of arguments provided in an array:

var params = [0, Activities.length].concat(_json);
Activities.splice.apply(Activities, params);

This alternative approach achieves the same result as before but includes all elements from _json.

Additional Resources: concat, splice, apply

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

Extracting information from dynamically generated tables using Python 2.7, Beautiful Soup, and Selenium

I am in need of assistance with scraping a JavaScript generated table and saving specific data to a csv file. The tools available to me are limited to python 2.7, Beautiful Soup, and/or Selenium. Although I have referred to the code provided in question 14 ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Creating a multidimensional array or array tree from a list of arrays - A step-by-step guide!

My challenge involves working with an array that looks like this: ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"] The goal is to create subarrays with a combined character length of 10, resulting in something like this: [ ["Lorem", "Ipsum"], ...

The for loop is not receiving any values

This is puzzling me a bit. I am facing an issue with two functions in my code: 1) var revisionNumber; var $list = $('<ul>'); TFS_Wit_WebApi.getClient().getWorkItem(284) .then(function(query) { revisionNumber = query.rev; ...

Implementing a JavaScript function with parameters onto an element using backend code

Hey everyone, I've run into a strange issue while trying to pass string parameters to a JavaScript function from the code behind. Here is the current code snippet that I believe is causing the problem: thumbnail = "<a href = 'javascript:Remov ...

Eliminating the dependency on Angular $http in a custom JavaScript library

Is there a way to develop a versatile JavaScript library that can be utilized across different frameworks, while still being able to leverage Angular's $http service when necessary? Would it be feasible to incorporate jQuery as a fallback for other fr ...

Is there an issue with using $_POST in an ajax form submission?

Whenever I attempt to verify if a user-inputted name already exists through an ajax form submission, all I receive is an error stating "Undefined index: username" in the sessions.php file. What could be causing this issue? <form action="" method="POST" ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

Ways to extract particular keys from a JSON array?

I am receiving an array of JSON objects in my response. {"took":0,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{" ...

The datetimepicker is not functioning properly

I'm experiencing an issue with the datetimepicker where it doesn't display a calendar when I click the icon. Interestingly, the Chrome browser isn't showing any errors in the development console. <script src="Scripts/jquery-2.1.1.min.js ...

Ensure that a form field is validated using a dynamically assigned name in Angular

Generating a dynamic form in the view involves iterating through an object containing various user questions. Each question has a unique attribute called formFieldName, which assigns a random string as the field name. <form name="includedForm.newReques ...

The XMLHttpRequest is displaying additional characters within its response

Upon completing an XMLHttpRequest(), I am receiving the unexpected output of "true↵↵↵". In my php file, all I have is echo json_encode(true); Can anyone shed some light on why this strange behavior is occurring? Thank you ...

Storing JavaScript-created DOM nodes in MySQL using a combination of jQuery AJAX and PHP

I am working on a basic Javascript client script that includes an HTML button. This script, when clicked, generates new DOM nodes, each with a unique ID based on an incrementing counter. As each node is created, its name (div1, div2, div3, etc) is added to ...

Ways to display and conceal menu depending on initial view and scrolling

On my website, I have implemented two menus - one to be displayed when the page loads and another to show up when a scroll occurs. You can view my page here. The goal is to have the white part visible when the position is at the top, and switch to the blu ...

Choose the current parent item using Angular's ng-selected and $index

http://plnkr.co/edit/fwwAd4bn6z2vxVN2FUL7?p=preview On the Plunker page linked above, I am trying to achieve a specific functionality. I would like the 3 dropdown lists to display values A, B, and C initially. When a 4th dropdown option is added, it shoul ...

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

Restrict form submission when minimum and maximum requirements are not met using JavaScript

I'm currently using JavaScript to show an error message when a user clicks on the form submit button and the entered number is not within the specified min and max range. The problem I am facing is that even when the submit button is clicked, the form ...

AngularJS: Issue with directive function not being executed

I created a directive in my code, but for some reason the function I provided to define the directive is not being called. It was working perfectly fine before, and now it just suddenly stopped without any clear explanation. Below is the code snippet of m ...

Trigger the "onChange" event when the input element is modified by JavaScript within a popup window

On my webpage, I have a form element and a popup window (which is opened using window.open). Both the form element and the popup window utilize jQuery. The JavaScript in the popup window has the ability to alter the form element on the main page successf ...