Issues with sending parameters via an initialisation function in JavaScript

I am struggling with passing arguments to a new object when using an initializer function. Let's look at my examples where I aim to create an object that returns an array. Object Ex1 works as expected:

Ex1 = function() {

    myVar = [];
     myVar = Array.apply( myVar, arguments );
     return myVar;

};

ex1 = new Ex1( 'red', 'green', 'blue' );
console.log( ex1);
/* ["red", "green", "blue"] */

However, I prefer using an initialiser for cleaner code. Object Ex2 demonstrates the issue I am facing:

Ex2 = function() {

    init = function() {
         myVar = [];
         myVar = Array.apply( myVar, arguments );
         return myVar;
    };

     return init( arguments );

};

ex2 = new Ex2( 'red', 'green', 'blue' );
console.log( ex2 );
/* [[object Arguments] {
   0: "red",
   1: "green",
   2: "blue"
   }] */

The log shows the result is not a neat array.

How can I ensure that I get an array when creating a new object by using an initializer function and passing arguments to it?

Answer №1

This issue is fairly straightforward to grasp. Within a function, the arguments object resembles an array containing all passed arguments. So in your second scenario, when you pass an array as an argument to the init function, the arguments within that function becomes a two-dimensional array.

Ex3 = function() {   
    init = function() {
        myArr = [];
        myArr = Array.apply(myArr, arguments); //arguments: [["red", "green", "blue"]]
        return myArr;
    };

    return init(arguments); //arguments: ["red", "green", "blue"]  
};

You could also make use of parameters like this:

Ex3 = function() {
    var init = function(arg) {
        return Array.apply(0, arg); //arg: ["red", "green", "blue"]
    };
    return init(arguments);
};
ex3 = new Ex3('red', 'green', 'blue');
console.log(ex3); //["red", "green", "blue"]

Remember, declaring a variable without using var will result in it being placed in the global scope.

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

Dividing internal CRUD/admin panel from the live application

Currently developing a moderately complex react app with redux. We have a production version that meets our requirements and now we are working on an administrative area for a local version of the application. This local version will only have basic CRUD f ...

``Unresolved issue: Sending emails using Sendgrid and Firebase not working in production through Netlify

For a simple contact form, I am utilizing Nuxt, Sendgrid, and Firebase. Netlify is being used for hosting the project. The contact form works perfectly fine locally and sends emails without any issues. However, once I push the project to Netlify, the email ...

Adding HTML and scripts to a page using PHP and JS

Currently, I am utilizing an ajax call to append a MVC partial view containing style sheets and script files to my php page. Unfortunately, it seems that the <script> tags are not being appended. After checking my HTTP request on the network, I can ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Troubles with proper functionality of antd's DatePicker.RangePicker within a React Function Component

I am currently utilizing React and the antd library, attempting to incorporate the DatePicker.RangePicker into my project. Initially, when I directly embed the RangePicker within the component, everything works smoothly. However, for better code organizat ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

Exploring the functionalities of Express and Socket.io

I am new to creating a Node.js app using express V 3.4.8 and socket.io V 0.9.16 to display a map with markers showing where users are connecting to the site. I am doing this to learn more about node.js and how to incorporate maps into my projects. However, ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Ar.js results in objects experiencing deformation or modification when manipulated

Recently, I started experimenting with Ar.js and encountered an issue where the objects displayed on the screen seemed distorted. To illustrate this problem, let me share a basic A-Frame example featuring a perfectly round sphere: <!DOCTYPE> <html ...

Create a duplicate <li> element and animate it using jQuery

Here are the list items: <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</l ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

Tips for preventing multiple clicks when posting AJAX requests in jQuery

Using Django, I was able to create a website and implement a voting page with jQuery AJAX. The code works perfectly fine as shown below: <!doctype html> <html> <head> <script src="jquery-1.10.2.min.js"></script> <met ...

The current issue with this javascript function is that it is failing to produce any output

function calculateOverallCGPA() { let cumulativeGPA = 0.00; for (let i = 1; i <= semNum; i++) { const GPAforOneSubject = parseFloat(getElementById(`subs${i}`).value); cumulativeGPA += GPAforOneSubject; } const finalCGPA = ...

``There appears to be an issue with the functionality of the jQuery

I've been experimenting with using AJAX in a PHP form, but for some reason it's not working as expected. I'm at a loss trying to figure out why. Here is my code: <!DOCTYPE html> <html lang="es"> <head> <title>< ...

How come the Array object transforms into an empty state when an input file is passed as an array element in an ajax request without

When attempting to upload a file without assigning it to an array, the process works fine. However, when trying to assign the file object as an element of an array, $_FILES becomes empty. HTML <input type='file' name='image' class= ...

In CodeIgniter, when there are multiple entries with the same ID in a foreach loop, the elements can be summed

I am using a foreach loop to create a table with data from the "sale" row, specifically json_decode($row['sale']). Currently, each entry is being displayed separately. However, my goal is to display entries with the same id [product_id] as one ro ...

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML an ...

Navigating with Express while incorporating React

I am struggling to set up the routes for my web application using Express, as well as incorporating React for the front end. The issue lies in properly routing things when React components are involved. My index.html contains: <script> document.get ...

Mantine UI: Elevate Your Component Library Experience

I am in the process of creating a Component library for internal company projects, which will be packaged as an npm package. To kick things off, I am starting with Mantine and plan to incorporate customization using tailwind CSS. As a test, I have created ...