The Array.from function produces an array containing undefined elements rather than actual numbers

I recently wrote this code snippet:

let nums= Array.from({length:7},(curr,i)=> { console.log(curr,i);  i+1;})
console.log(nums); // which results in [undefined *7]

I am puzzled as to why the array nums is not initialized with numbers from 1 to 7?

Answer №1

To retrieve the correct value, make sure to actually return it instead of just incrementing. If you fail to do so, you will end up with an undefined result.

const output = Array.from({ length: 7 }, (item, index) => index + 1 );
console.log(output)

Answer №2

When you don't return anything from the function passed to Array.from, it defaults to returning undefined. This results in an array filled with 7 undefined values.

let abcd= Array.from({length:7},(curr,i)=> {
  console.log(curr,i); 
  return i+1;
})
console.log(abcd); // returns [undefined *7]

An alternative method to achieve the same result is by using the spread operator and map() function.

let abcd = [...Array(7)].map((x, i) => i + 1)
console.log(abcd); // returns [undefined *7]

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

Deletion of a custom function in JavaScript

I have written some basic code to generate and remove an image using functions. Specifically, I need help with removing the image created by the function Generate() when a button linked to the function Reset1() is clicked. Here's the code snippet for ...

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

A solution to determining the size of an array in C++ by using a variable within square brackets

The following code snippet shows my dilemma. I am attempting to declare an array with a size represented by variable n. FILE *fp; fp=fopen("myfile.b", "rb"); if(fp==NULL){ fputs("file error", stderr); exit(1); } int* a; fread(a, 0x1, 0x4, fp); int n=*a; i ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

What is the process of transforming an xhr request into an angular $http request?

I've been successfully loading images using ajax with the following code. However, when trying to convert it into Angular and use $http, it's not working as expected. Original ajax code var xhr = new XMLHttpRequest(); xhr.open('GET', ...

Retaining original input value even when validation is applied with input type="number"

Encountering an unusual scenario while using angularJs and input type="number". It seems that if the initial value of an input falls outside the specified min and max range, the value gets wiped out. To better visualize the issue, I created a fiddle - htt ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Converting a browser buffer to a string may not yield the same result in both a browser environment and

I've come across a puzzling problem while using node v8.1.4. Here's the buffer I'm dealing with: [ 191, 164, 235, 131, 30, 28, 164, 179, 101, 138, 94, 36,... ] When attempting to convert it to utf8 in both Node.js and the browser, I notic ...

Refresh information in the never-ending roster

I'm dealing with a component - items list that has infinite scrolling. As it scrolls down and adds elements to the list, it's not populating them with the received data (the array with new data is being received, but the newly added elements are ...

AngularJS: Enhancing User Input Experience with Bidirectional Data Binding for Numeric Inputs

I'm exploring the use of Angular for data-binding with input type="number" elements, but I'm encountering difficulties in getting the binding to work. When I make changes to any value, I expect the corresponding binded value to update as well. J ...

AngularJS does not clear the array after a POST request is made

ISSUE Greetings! I am encountering an odd behavior with my backend. When I submit data, everything works flawlessly. However, if I press ENTER and submit an empty field, it reposts the previous value. Initially, I cannot submit an empty field, but after e ...

What's the best method to call a PHP file using AJAX/JavaScript?

I am having an issue with my code that uses AJAX to GET a PHP file. The main objective is to notify the user whether the movie table is empty or not. If the table turns out to be empty, a confirmation box will pop up asking the user if they want to add mov ...

Arranging an array of objects based on dual criteria

Sorting an array of objects based on 2 conditions is my current challenge First, I need to sort by value If the names are the same, I want to display them next to each other in ascending order of their values For a visual example, check out this demo: ht ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...

Encase the text within a div element while leaving out any child elements

I have encountered a puzzling issue that has been troubling me for the past two days, and I have yet to find a solution. The Dilemma: Here is the HTML code in question: <div class="string-box"> Text 1 wrap me <span clas ...

Extract the initial row of data from a CSV file and divide it into two separate DIV elements

My goal is to display the first two entries from a Google Spreadsheets CSV into two separate divs. This is crucial for my dynamically updating gallery, where the first line of the CSV should already be visible when the page loads. Subsequently, my JavaScri ...

What could be behind the TypeError that is showing up in the gulpfile?

My Development Environment Currently, I am in the process of building a web application utilizing Bootstrap v4.0.0-alpha.3 and Gulp.js v.3.9.1 to automate tasks within the Webstorm 2016.2.3 IDE. The environment I am working on is macOS Sierra version 10.1 ...

The offsetLeft property in Jquery does not function properly when scrolling to the right

I am looking to update the left position while scrolling using the arrow keys or middle mouse button, rather than just when scrolling up or down. My current script is as follows: $(window).scroll(function() { var scroll = $(window).scrollTop(); if(scrol ...

Learn about ng-show in AngularJS

Is there a way to hide this tag if it doesn't have a subcategory? I tried using the condition item.length != 0 but it doesn't seem to be working properly. <multi-select-tree class="multiselectStyle groupStyle" data-input-model="ca ...

What is the best way to trigger the Reactjs MUI DatePicker popup to display when clicking inside it for editing the date, without relying on the

As of now, DatePicker displays a calendar icon for opening the date picker popup. While I can eliminate the icon using the disableOpenPicker property, my goal is to open the popup when the user clicks on the Datepicker input field, functioning just like ...