JavaScript Array - Error: Unable to access property 'length'

Currently, I am working on a Cordova/Phonegap application that utilizes an internal database. Typically, after executing a query, I would retrieve and review the results as shown below:

for (var i=0;i<results.rows.length;i++)
{
     name=(results.rows.item(i).name);
     alert(name);
}

However, due to issues with the RANDOM() SQLite function, as discussed in this thread, I decided to manually shuffle the results:

function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}
var resultArray = [];
for(var x=0; x < results.rows.length; x+=1) {
     resultArray.push(results.rows.item(x));
}
var res = shuffle(resultArray);
for (var i=0;i<res.rows.length;i++){
     name=(res.rows.item(i).name);
}

ERROR:

Uncaught TypeError: Cannot read property 'length' of undefined

I am currently encountering this error. Could you please explain why this is happening and provide guidance on how to resolve it? Thank you!

Answer №1

let shuffledResults = shuffle(resultArray);
for (let i=0; i<shuffledResults.length; i++){
     name=(shuffledResults.item(i).name);
}

Is that correct?

Or would this be more efficient?

let shuffledResults = shuffle(resultArray);
for (let i=0; i<shuffledResults.length; i++){
     name=(shuffledResults[i].name);
}

If not, please check the console for any errors:

let shuffledResults = shuffle(resultArray);
console.log(shuffledResults);
for (let i=0; i<shuffledResults.length; i++){
     name=(shuffledResults[i].name);
     console.log(shuffledResults[i]);
}

P.S. Remember, all values are being stored in the same 'name' variable - they may overwrite each other

Answer №2

To populate the resultArray with items that do not have rows, it is essential to iterate through the resultArray only.

resultArray.push(results.rows.item(x));

Therefore, implement the following code:

var shuffledResults = shuffle(resultArray);
for (var j=0; j < shuffledResults.length; j++) {
    title = (shuffledResults[j].title);
}

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 access the values associated with the keys in an array of objects?

I have an array of objects that has the following structure: import icon1 from '!!raw-loader!../../../icon1.svg'; import icon2 from '!!raw-loader!../../../icon2.svg'; import icon3 from '!!raw-loader!../../../icon3.svg'; import ...

What could be causing the Quasar drawer to overlap the Quasar toolbar in a Vue application?

I am currently utilizing the quasar UI framework and have a main layout file that includes only a toolbar. This toolbar is meant to display across all pages in my application. <template> <q-layout view="hHh Lpr lff" style="backgro ...

I am looking for the best way to sort my JSON data based on user roles before it is transmitted to the front end using Express and MongoDB. Any

I scoured the internet high and low, but to no avail - I couldn't find any framework or code snippet that could assist me in my predicament. Here's what I'm trying to achieve: whenever a response is sent to my front-end, I want to filter th ...

Using AngularJS client and Flask server for a RESTful call, one can include the

I am currently facing an issue where I need to send a REST request from my AngularJs client to a Flask server. The problem arises when one of the ids (key) in the request contains a forward slash. Interestingly, if the key does not contain a slash, the re ...

issues encountered when attempting to modify the background color of navigation items using bootstrap

Presently, I am focusing on enhancing the navigation bar of my website, but I have encountered an issue with my JavaScript code. I have implemented a scroll-spy feature in my navigation and added JavaScript for smooth scrolling. Additionally, I aim to make ...

Are there any similar tools to Graphstream in Java that can be used with HTML5 using canvas and JavaScript?

GraphStream is a revolutionary graph library created in Java that offers Java developers a simple way to visually represent dynamic graphs either in memory, on screen, or in files. Check out this demo video. With GraphStream, you can effectively handle th ...

Extract the URL from an iframe using either coding techniques or through user interaction

I am in the process of creating a website that will serve as a wrapper around a third-party site using an iframe. My goal is to allow users to browse the third-party site within the iframe, then share the URL with the main site for storage. My objective i ...

Error: Unexpected character encountered

When attempting to parse an array of objects enclosed in double quotes, I encountered an error: Uncaught SyntaxError: Unexpected token ' var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' ...

Is event delegation in React similar to jQuery's `on()` method?

Just starting out with React.js and I've built a list Component that has items being added and removed frequently. Each item needs to have click and/or hover events. I'm looking to implement event delegation similar to how it's done in jQue ...

Guide to integrating the office-ui-fabric-react library into your current MVC project

Our team has embarked on developing an application and we've decided to integrate it with office-ui-fabric-react. While I am familiar with installing packages using npm, I am unsure about where to install both NodeJs & gulp. I have a repository na ...

Unable to send multiple onChange AJAX requests

Why do I keep getting the error Notice: Undefined index: provinsi when trying to retrieve values from tahun and provinsi using this code? If I remove provinsi from the code and only use tahun, I am able to successfully fetch data from my database. func ...

Calculator built with HTML, CSS, and JavaScript

Hi there, I'm experiencing some issues with my calculator. The buttons seem to be working fine and lining up correctly, but for some reason, nothing is showing up on the monitor or getting calculated when I press the buttons. Here's the code that ...

Error message encountered while attempting to search on Wikipedia: "Unable to connect to *ngFor" (Angular2 / HTML / Javascript)

I am currently working on developing a search bar that will search through data and display the results based on the input in the search box after clicking a button. The data can be sourced from Wikipedia or local fake data, it doesn't make a differen ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

The message "Missing property 'type' in type 'typeof WithXXX'" indicates an error

Currently, I am working on a project using React in combination with Typescript. My goal is to create a higher order component based on the react-dnd library. The problem arises within the DragSource section of the react-dnd component. Here is the relevant ...

Ways to prevent npm script from running automatically in the background

When working with npm scripts, I have a situation where some tasks need to run in parallel. My setup looks something like this: ... scripts: { "a": "taskA &", "preb": "npm run a", "b": "taskB" } ... Everything works well so far! But I am won ...

Implementing a password prompt in CodeIgniter using JavaScript

I need to delete a teacher as an admin, but before doing so, I want to require them to re-enter their password. However, I'm having trouble getting the delete function to work even though the prompt is displayed. Can someone help me figure out what I& ...

Accepts numerical values and a single comma

Is there a way to restrict an input field to accept only numbers and exactly one comma? Here's the approach I've been using: $("#my-field").on("keyup", checkKey); function checkKey() { this.value = this.value.replace(/[^0-9,]/g, ""); } ...

Calculate the total duration between two times and, if the difference is more than 10 minutes,

I need to calculate the duration between two dates, start_time and end_time. If the minutes component is greater than 10, I want to round up the hours component. For example: 12 minutes different - rounded up to 1 hour 1 hour 31 minutes difference - roun ...

Observing changes in the height of an Angular directive

I've encountered an issue where I can't seem to get the code working properly even though the question has been asked before. Within my directive, I have found that the following piece of code functions correctly when the element's height i ...