Operating with an array as an array is not possible

Currently, I am in the process of creating an array structured like so:

var p1_s1 = {
            'title': 'p1_s1', 'titleDisplayed': 'p1_s1', 'type': 'numbers', 'page':1,'strings': 1, 'length': 7, 'placeholder':'0000000', 'painted':'black', 'notPainted':'#ffe485', 'left':410, 'top':161, 'width':394, 'height':144,
            'ids':[
                    ['path5472','path5440','path5488','path5520','path5504','path5456','path5536'],
                    ['path5360','path5328','path5376','path5408','path5392','path5344','path5424'],
                    ['path5584','path5552','path5600','path5632','path5616','path5568','path5648'],
                    ['path4912','path4880','path4928','path4960','path4944','path4896','path4976'],
                    ['path5024','path4992','path5040','path5072','path5056','path5008','path5088'],
                    ['path5136','path5104','path5152','path5184','path5168','path5120','path5200'],
                    ['path5248','path5216','path5264','path5296','path5280','path5232','path5312']
                    ]
    };

Subsequently, within my script code, I make use of this variable by calling it:

...
var ids = p1_s1['ids'];
        for(var i = ids.length;i>=0;i--)
        {
            drawOneNumber( ids[i], parseInt(value[i]) );
        }
...
function drawOneNumber( place, number )
{
    number = numberToSegments( number );
    console.log(place);
    for(var i=0;i<number.length;i++)
    {
        console.log( place[i] );
    }
    ...
}

Upon utilizing console.log(place);, the array is outputted on the console as expected.

(7) […]
​0: "path5248"
​1: "path5216"
​2: "path5264"
​3: "path5296"
​4: "path5280"
​5: "path5232"
​6: "path5312"
​length: 7
​

However, when attempting to log place[i], an error occurs:

TypeError: place is undefined

The same issue arises with the following code snippet:

place.forEach(element => console.log(element));

Even though Array.isArray(place); returns true, manipulating this variable as an array seems to be problematic. Could you please advise on where I might be going wrong? Thank you.

Answer №1

The issue arises from the for loop logic

Consider this: If your array has a length of 5, the last element will be accessed at the 4th position.

Since you have defined i = ids.length and are trying to access ids[i], it will return undefined leading to an undefined variable place in your drawOneNumber function as well.

For instance:

const arr = ["foo", "bar", "youhou"];

console.log(arr.length);
console.log(arr[arr.length]);

It is better to use :

for(var i = ids.length -1 ;i>=0;i--)
instead.

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 change the content in a textarea field?

I am looking to create a functionality where a div is displayed below selected text inside a textarea. Below is the JavaScript code: function getSel() { var txtarea = document.getElementById("mytextarea"); var start = txtarea.selectionStart; ...

Struggling to update a Knockout observable array

I'm attempting to send some data to a Knockout observable array. Despite receiving data from my AJAX call without any errors during script execution, I find that the userNames array remains empty when accessed. What could be causing this issue? UserH ...

Uploading custom images with a WordPress widget

I have been occupied with developing my own WordPress Widget, and almost everything is functioning smoothly except for the WordPress media uploader. I have incorporated eight buttons and input text fields to store the URL of the uploaded image. The click ...

Is it possible to copy text from an iframe to the clipboard?

I have encountered an issue in my React app where I am trying to copy text from a card when the user clicks on it. The app displays multiple cards by looping through an array, so there can be any number of cards (n). The problem arises because the React a ...

Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it. At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links. Here is an example of a s ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

Looking to obtain the coordinates of a draggable element?

After dragging a div around the page and submitting a form, I would like to capture its location on the page so it can render in that same spot when the page reloads. My current question is how can I capture the coordinates or location of the div after it ...

Rearranging an array using the numbers contained within the array elements in JavaScript

I'm currently working on unscrambling an array. The array contains string elements that are not in the correct order, with numbers attached to indicate their desired position. My goal is to extract these numbers from each item and rearrange them in a ...

Encountering the error message "undefined is not a function" while attempting to retrieve JSON data

I'm running into some issues with retrieving data from a PHP file. Upon calling the variable msg[0}, I'm getting an undefined error even though it should have been filled in during the JSON request. The JavaScript code is provided below, and you ...

Utilizing jQuery for serializing unorganized lists

I have created multiple lists within a list and I need to pass the IDs using jQuery to another PHP file (updateDB.php). I attempted to serialize the list data but was unsuccessful. I'm not certain if I have implemented it correctly, I searched extens ...

Accessing a Global Variable within a Node Express Class Module

Within my Node Express application, I defined a variable in app.js like so: let accounts = [checkingAccount, savingAccount] Now, I have a class file named account.js (not a route) and I need to access the accounts array from within it. How can I achieve t ...

Navigating to the parent Vue component in a Vue3 project with Composition API structure in WebStorm

After transitioning to Vue3 and embracing the Composition API style, I find myself missing a small convenience that I had when developing in the previous Options API pattern. In WebStorm/IntelliJ IDE, I used to be able to command-click (Mac) on the "export ...

Add a click event to elements that match

I must admit that I am not particularly knowledgeable in Javascript/jQuery and my question might come across as trivial. However, I am trying to assign a click event to every element on the page with the following code: $(document).ready(function () { ...

Implement vertical navigation arrows in a Bootstrap accordion using JavaScript

Snippet of my HTML code: <div class="panel" style="margin-left: -15px;"> <div class="panel-heading"> <div class="vgroupholder panel-title" data-parent="#accordion" data-toggle="collapse" href=".titlePhysi ...

Converting an array into a table format with SimpleXMLobject in PHP

Array ( [0] => Array ( [Title] => SimpleXMLElement Object ( [0] => aa ) [Pubdate] => SimpleXMLElement Object ( [0] => ...

Mastering JavaScript Loops

Looking to create an endless loop of links that never stop? I need assistance achieving this. setTimeout(linkToGoogle, 5000); function linkToGoogle() { document.getElementById('myAnchor').innerHTML="Visit Google"; document.getElementById(&a ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Maintain the values of variables established in a userscript

Currently, I am working on a Tampermonkey script and facing an issue. In my script, I declared an array as var arr = ["alex", "felix"] which can be updated dynamically based on the script's usage. Each time there is a change, I update the value by ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

"Unlock the power of Angular.js: Extracting table row data with the click of a checkbox

Can anyone help me with this? I am trying to retrieve all checked data from a table row using Angular.js. Below is my code: <tr ng-repeat="gl in galleryDatas"> <td><input type="checkbox" name=""> {{$index+1}}</td> <td><img ...