ajax does not function properly with arrays

i'm currently attempting to load data from a text file into an array using ajax, and this is the code i am utilizing:

function loadWords(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "dico/francais.html");
    xhr.onreadystatechange = function(){
        if(xhr.readyState == xhr.DONE && xhr.status == 200){
            dico = xhr.responseText.split("\n");
            for(var i=0; i<wordsNBR; i++){
                var x = Math.floor(Math.random()*dico.length);
                words[i] = dico[x];
            }
        }
    }
    xhr.send(null);
}

the original code works as expected. However, when attempting to modify the following portion:

for(var i=0; i<wordsNBR; i++){
                var x = Math.floor(Math.random()*dico.length);
                words.push(dico.splice(x,1));
            }

I encounter an issue where it no longer functions as intended. Does anyone have any insight into why this may be happening?

Answer №1

section, you can find an explanation of how dico.splice(x,1) functions by altering the array and giving back the eliminated element. It is recommended to use this when x is less than dico.length, as it randomly chooses a word from the dico array. The most likely error is simply using the incorrect variable. Yet another mistake is forgetting that splice returns an array rather than just one element. To obtain the desired element, one needs to include dico.splice(x,1)[0]. You can correct these errors by following these steps:
var x = Math.floor(Math.random()*dico.length); // chooses an index from the remaining elements in dico
words.push(dico.splice(x,1)[0]); // eliminates the word and appends it to words list

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

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

JavaScript DateTimePicker onChange event malfunctioning

Issue with JS datetimepicker onChange event not functioning. Attempts have been made using OnSelect, OnClose, OnChange, OnHide, OnChangeMonth to trigger the datetimepicker event, but none of them seem to be effective. <input type="text" class="form-co ...

Tips for efficiently organizing and maintaining a selection of JavaScript variables by easily adding and removing them as needed

I am currently developing items that will be shown on a webpage. I achieve this by utilizing the following code: var popup = "something..." Is there a method to keep track of all the created popup variables and control them efficiently using: adding a ...

Adjusting height in Google Maps to fill the remaining space

Currently, I am developing a map application where I want the Google Maps DIV to occupy the remaining height under the header. Here is the code snippet: <!DOCTYPE html> <head> <title>Map Application</title> <style type ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

I am facing issues with installing React Router on my Windows device

After running the command to install react-router, this is the output from my prompt window: npm install --save react-router The prompt window shows several warnings and optional dependencies: npm WARN @babel/core requires a peer of @babel/core@^7.13 ...

How can I retrieve console log information in POSTMAN when a test fails?

Having an issue with this test. I am trying to trigger a console.log when the installment value in my JSON is less than 100 (resulting in a test FAIL). However, I am receiving both PASS and FAIL results in the test, but no information is showing up in th ...

Unable to set values to an array of objects in JavaScript

Currently, I am facing an issue in my node.js project where I am unable to assign values to an array of objects. This problem has occurred before, but I just can't seem to figure out the root cause. My suspicion is that it might be related to variable ...

Sending a Single Input Field value to a Controller in Laravel using JQuery

Looking to submit a single form value using jQuery to a database in Laravel. Below is the input field: <input type="text" id="comment"> <button id="cmntSubmit" type="button">Post</button> Check out the jQuery code I am using: $(docum ...

Having trouble with your Discord.js Bot continuously going offline and getting Value errors? Here’s how to resolve it

Why do I keep encountering this error? TypeError: Cannot read property 'size' of undefined at Client.client.on.message (/home/colter/Code/groundskeeper/index.js:38:30) at emitOne (events.js:116:13) at Client.emit (events.js:211:7) at MessageCre ...

Top method in Angular 6 for verifying if a scrollable section has been scrolled to the very bottom

I am searching for a reliable solution in Angular 6 to determine whether a scrollable host component has reached its maximum scroll bottom. Despite my efforts, I have been unsuccessful in finding a functioning example of a function that can detect if a cu ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...

What is the best way to use a CSS class in my script specifically for specific screen sizes?

Utilizing bootstrap 4, my code is executing a for loop to generate eight divs with the class "item". To display five items per row, I am using the class "col-2". However, this results in six items being shown in a single row. Since I cannot include the o ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

Acquire information using Vue through HTTP requests based on Router parameters

I have been searching for a solution to this issue and even referred to the example provided on the Vue Router documentation, but I am still encountering difficulties. My goal is to make an HTTP call when a component loads initially, then monitor the route ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

submitting a POST request with JSON payload including an array

Resolved. To solve this issue, you need to set the contentType to 'application/json' and use JSON.stringify(obj) instead of obj. However, keep in mind that you may need to adjust how you retrieve the data on your server, depending on the language ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

Receiving accolades within a nested function while implementing a Higher Order Component

I'm currently working on creating a Higher Order Component (HOC) to manage some functionalities in React. Here is my implementation: import React, { useState } from "react"; export default function withFormControl(WrappedComponent) { return props ...

Using Selenium to handle asynchronous JavaScript requests

Having recently started working with Selenium and JavaScript callback functions, I've encountered a problem that I can't seem to solve on my own. My issue revolves around needing to retrieve a specific variable using JavaScript. When I manually i ...