Why is this function returns an empty array?

klarate

I just don't understand why does this function return an empty array instead of newArr = [1, 2, 3, etc.] depending on the length of the array.

function randomFunction(num) {
      var newArr = [];


      for(var i = 1; i < num.length; i++) {   
          newArr.push(i);
     }

      return newArr;
 };
Alberto Trindade Tavares

If num is supposed to be the length of the new array, and the last number of the range of values, you have to use it directly, instead of using length (which is meant to be used for an array):

function randomFunction(num) {
     var newArr = [];

     for(var i = 1; i <= num; i++) {   
        newArr.push(i);
     }

     return newArr;
 };

 var array = randomFunction(5);
 console.log(array);

Also, you might want use <= instead of <, in case you want to start the value by 1 and go through n, and not n - 1.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why passing function object to Object.keys() returns empty array?

Google Cloud Function - Why bucket always returns empty array of files?

Async function returns empty array

Why Laravel query returns empty array?

empty() function returns false although array contains empty array

Why is my array not empty in the onBeforeMount function but empty in the onMounted function

why Object.keys(Array.prototype) returns empty array?

Why the array returned by the combinationSum function is empty (Javascript)?

Why is my array empty at the function that receives it in React?

Why is my function returning an empty array?

Why function returns filtered boolean array

Why every? function returns true with empty vector in Clojure?

Why is this async function returning empty on the first try, but then it returns everything?

Why a function checking if a string is empty always returns true?

Why React returns empty when calling a function for the first time?

Why second run of a function in for loop returns an empty string?

Why the below function is not returning any value and it is always returns empty

Why does MongoDB $size returns 1 for an empty sub-array?

Why returning values from sqlite returns an empty array

while adding empty array and object, why console returns like this?

Why laravel returns an empty array for a has many relationship?

Why String.prototype.match() returns null instead of empty array?

Why only inserts one object in list and returns empty array

Twitter: Why statuses/user_timeline.json returns an empty array?

why does a Uint8Array() from buffer returns empty?

Why GetAllActorsOfClass returns empty?

Trying to mutate a string in a function with a few pipes returns empty array

Return Firebase Database Array To Another Function But Returns Empty

Context with React Native hooks returns empty object/array on async function