Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript.

In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization.

For example, a 1-D vector of size 3 would appear as (0.0 0.0 0.0)T, with T indicating the transpose of the vector.

A 3 x 3 matrix would be initialized as:

[0.0 0.0 0.0;
0.0 0.0 0.0;
0.0 0.0 0.0]

This feature in C++ streamlines the code and enhances program efficiency by avoiding unnecessary repetition.

Is there a similar functionality in JavaScript? If not, I will resort to explicit initialization:

For instance, Code:

for (let i = 0; i < N; ++i) {
    v[i] = 0.0;
}

Alternatively, can someone suggest the most efficient method for initializing 1-D and 2-D arrays to 0.0 in JavaScript?

Answer №1

One option with ES6 is to utilize Array#fill.

By using var array = Array(3).fill(0);
//                ^           specifies the size of the array
//                        ^   defines the value of each element

For ES5, you can achieve this as follows:

var array = Array.apply(null, { length: 3 }).map(function () { return 0; });
//                                      ^                                    determines the length of the array
//                                                                    ^      sets the value for each element

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

Avoiding external variable reference through Jest.mock

For snapshot testing, I need to create a simple dummy mock of 1 react component. When attempting to use React.Component within the mock function, an error is thrown: The second argument of jest.mock() cannot reference external variables. However, usin ...

A guide to using loops in PHP to separate and allocate data within a multi-dimensional array

A script provides me with an associative array of data: while($row = mysqli_fetch_assoc($query)){ $replyArray[] = array( 'did' => $row['discussion_id'], 'rid' => $row['reacter_id'], ...

When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I' ...

Effortless script to make a URL request and display the response status | using JavaScript with jQuery

Is there a way to use JavaScript or jQuery to request a URL or website address and display the response code? For example: request www.google.com if (response_code = 200) { print "website alive" } else if (response_code = 204) { print "not found"; } ...

Creating a smooth sliding textarea in HTML

I am working on creating an HTML table with numerous text input areas (textarea) that expand downwards when clicked. Currently, the textarea element expands properly but disrupts the layout of the table. My goal is to achieve a design like this Instead o ...

Angular components are not receiving the Tailwind CSS attributes applied to :root classes

In my Angular 12 project, I have integrated Tailwind CSS. The structure of the package.json is as below: { "name": "some-angular-app", "version": "0.0.0", "scripts": { "ng": "ng&quo ...

Streamline the process of renaming or remapping keys in a collection of JavaScript/JSON objects

Structured JSON data is essential. Imagine using JSON.parse(): [ { "title": "pineapple", "uid": "ab982d34c98f" }, { "title": "carrots", "uid": "6f12e6ba45ec" } ] The goal is to transform it by changing titl ...

Monitoring page reload with JavaScript

Here is an example of tabbed content: <div class="tab"> <button class="tablinks" onclick="openCity(event, 'NewYork')" id="defaultOpen">New York</button> <button class="tablinks" onclick="openCity(event, 'LosAngeles& ...

Neglecting a light source in the Three.js framework

Currently, I am in the process of constructing a 3D hex grid and my goal is to integrate a fog of war feature. This is a glimpse of what the grid looks like at present: The lighting setup I have arranged is as follows: // Setting up hemisphere light var ...

Trouble with Installing Express

I have encountered an issue while trying to install express, despite following various solutions without success. Upon installation, I receive the message: npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb8c9e9988928f9 ...

Discovering Unconventional Columns Through Sharepoint REST Api Filtration

I am working on recreating SharePoint's front end in my app and want to add columns to my table just like a user would in SP. The challenge I am facing is determining which columns were custom generated by the user rather than standard ones. Although ...

The issue with Angular JS is that it fails to refresh the select and input fields after selecting a date

Currently utilizing Angular JS and Bootstrap, I have a query regarding updating the input for a datepicker calendar and a select from a function. The values are being successfully updated, however, they do not reflect on their respective inputs. It seems ...

How can I set the sphere's rotation in THREE.js to be absolute instead of cumulative?

I have encountered an issue with setting the rotation of a Three.js sphere to an absolute value. Whenever I use rotateY, the value I apply gets added or subtracted from the previous rotation instead of setting a new absolute rotation. In a similar scenari ...

Upon clicking a table row, generate a div underneath containing mapped data

My dynamic table is currently being filled with rows based on an array, but I want to display more data in an expanded view when a button in a row is clicked. However, I'm facing challenges as it seems I can't have two table rows within the same ...

Error: The middleware function is not recognized | Guide to Transitioning to React Redux Firebase v3

After utilizing these packages for my project, I encountered an error in middleware composition while creating a new react app with create-react-app. Below are the packages I have included. Can someone please help me identify what is missing here? HELP I ...

Exploring the Power of Namespaces in ECMAScript 6 Classes

My goal is to create a class within the namespace TEST using ECMAScript 6. Previously, I achieved this in "old" JavaScript with: var TEST=TEST || {}; TEST.Test1 = function() { } Now, I am attempting the following approach: var TEST=TEST || {}; class TES ...

Select a particular item and transfer its unique identifier to a different web page. Are there more efficient methods to accomplish this task without relying on href links and using the $_GET

Could there be a more efficient method for transferring the ID of a specific motorcycle from index.php to inventory.php when it is clicked on, aside from using href and $_GET? Perhaps utilizing hidden fields or submitting a form through JavaScript? What ...

What is the recommended TypeScript type for setting React children?

My current layout is as follows: export default function Layout(children:any) { return ( <div className={`${styles.FixedBody} bg-gray-200`}> <main className={styles.FixedMain}> <LoginButton /> { children } ...

Unable to generate a fresh database entry through form submission

I have designed User and Pairings models as shown below: class User < ActiveRecord::Base enum role: [:student, :supervisor, :admin] has_many :students, class_name: "User", foreign_key: "supervisor_id" belongs_to :supervisor, ...

Is there a way to disable logging for MongoDatabase connections?

After starting up my Node.js web server and connecting to the MongoDB database, I noticed that sensitive information including my password is being displayed in the console. This could be a security risk as the console may be publicly accessible on some ho ...