"At the beginning of an array in JavaScript, I often encounter the issue of receiving

Here is some code that I created:

function get_coordinates(container) {
    var x;
    var y;
    var divs = container.getElementsByTagName('div');

    Array.from(divs).forEach(div => {
        y += div.offsetTop+" ";
        x += div.offsetLeft + " ";
    });
    const a = x + ";" + y;
    console.log(divs);
    return x+";"+y;
}


Check out the output in the console:

HTMLCollection(10) [div#selector_1.selector, div#selector_2.selector, div#selector_3.selector, div#selector_4.selector, div#selector_5.selector, div#selector_6.selector, div#selector_7.selector, div#selector_8.selector, div#selector_9.selector, div#selector_10.selector, selector_1: div#selector_1.selector, selector_2: div#selector_2.selector, selector_3: div#selector_3.selector, selector_4: div#selector_4.selector, selector_5: div#selector_5.selector, …]

Now, take a look at the return value:

undefined0 0 0 0 0 0 0 0 0 0 ;undefined0 0 0 0 0 0 0 0 0 0

I'm puzzled as to why I'm getting undefined at the beginning of both strings.

Answer №1

As previously mentioned by Musa, it appears that you have not initialized x and y. As a result, the code you are attempting to execute is:

y += div.offsetTop + " ";
x += div.offsetLeft + " ";

Essentially, this translates to:

undefined += div.offsetTop + " ";
undefined += div.offsetLeft + " ";

To resolve this issue, it is important to define that x and y are strings at the outset. For example:

let x = "";
let y = "";

Additionally, I recommend utilizing let and const instead of var, as it is now 2022 and there is no longer a need for var.

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

Creating a webpage that loads directly to a specific section of content

After searching online, I couldn't find the solution I was looking for. My goal is to have the visible part of the page load halfway down the actual page. This way, when users visit the site, they can immediately scroll up to see more content. I hope ...

Data is present in a JavaScript array, yet it is returning a value of

In my quest to create an array of User IDs for an AJAX Post Request, I encountered a strange issue. Despite successfully retrieving and displaying the User IDs individually in console.log, once I push them to the connectionData array, accessing specific in ...

Node.js and Mongoose not functioning properly in collaboration

Searching for a user based on matching first and last names. router.post('/post/user/search/tag', function (req, res) { function getRegex(_query) { return { $regex: '^' + _query + '|.*' + _query, $optio ...

What is the reason for the absence of Duplex Stream in the Web Streams API?

I have experience working with the traditional nodejs stream, which makes the need for Duplex streams quite evident. These are streams that can both read and write data, like net.Socket. As mentioned here Examples of Duplex streams include: TCP sockets ...

Would it be possible to use a script to convert the y-axis values of the chart into Arabic numerals?

Currently, I am working on creating line and pie charts, but I need the Y-axis to display Arabic language. $('button').on('click', function(e) { $('#pie-chart3').empty(); var type = $(this).d ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

Is it possible for jquery JSON AJAX to block all users?

On my website, I use AJAX to load an RSS feed on the client side when the page loads. If a user repeatedly presses F5, could the owner of the RSS feed ban my entire website instead of just that one user? This would prevent others from loading the RSS feed ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

Is it possible to retrieve calculated data from a child component and pass it to the parent component?

Is there a way to transfer computed data from a child component to a parent component? Currently, I am passing data from the parent to the child first and then I would like to utilize the computed property (data) in the parent component. This is crucial as ...

"Troubleshooting a minor jQuery problem - update on current URL and refresh the page

I have developed a jQuery script that is designed to search through a webpage for specific text and then perform an action based on the findings. My query is straightforward. If I want to apply this script to a current website, such as www.google.com, how ...

JavaScript allows you to set an expiration date for a specific item

I am facing an issue with a form that contains inputs. On clicking the submit button, I want to capture the current time and add 10 hours to it before updating the table cell named expdate. Although I have a function in place for this purpose, it seems to ...

Stop iScroll from scrolling the listview filter

I have been working on integrating iScroll into my application using the javascript-jquery.mobile.iscroll plugin. My goal is to apply it to enable scrolling for a listview component on a specific page while keeping the filter fixed just below the header, a ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

Limit the input to numbers when pasting into Angular

Implementing a directive in <input type='text'> to restrict user input to numbers has been successful! The issue arises when a user copies and pastes a string, causing Angular to accept the value and send it to the backend. angular.module ...

Discovering the frequency of a specific key in a JSON object or array using JavaScript

Suppose I have a JSON object with the given data, how can I determine the frequency of the key: "StateID"? [{"StateID":"42","State_name":"Badakhshan","CountryID":"1"}, {"StateID":"43","State_name":"Badgis","CountryID":"1"}, {"StateID":"44","State_name": ...

Creating a project that utilizes Bing Translate and the Node.js programming language

As I work on developing a web application that enables users to translate text using the Bing translator API, I am facing an issue. I attempted to execute a translator.js file via a script tag, but encountered a roadblock since Node.js code cannot be run t ...

Explore the routing capabilities of the HERE Maps JS API, including features for ABR and height

Recently, I've encountered an issue with the HERE maps JS API routing feature. Specifically, I'm attempting to add restrictions based on factors like height or weight. Despite my efforts, it seems to be disregarding these restrictions. Additional ...

Render the React component asynchronously, only after the data has been successfully fetched

I am looking to display a component only after the necessary data has been fetched. If I try to load the data instantly, the component gets rendered but no information is displayed. class App extends React.Component { //typical construct fetchGameD ...

Troubleshooting: jQuery AJAX Post - Issue with Greater than conditional not functioning as expected

Having an issue with a conditional in my code. Everything is functioning properly except for this specific line. <if condition="$show['member']"> <script type="text/javascript" > $(function() { $("#submitbutton$post[postid]").click(f ...

Install package specifically for a single project

If I have the following file hierarchy: packages/project1 packages/project2 and the workspace is packages/* What is the best way to install an npm package for only project1 and not project2, while ensuring the yarn lock file includes the dependency? ...