Home > other >  Create array with function javascript
Create array with function javascript

Time:04-08

I need to create function that creates and returns array. Its size needs to match the rows parameter, and each next element contains consecutive integers starting at 1. To call this function I need to use argument 5. Here below is what I wrote so far. Can you tell me what's wrong here?

function createArray(rows) {
    for(let i = 1; i < rows.length; i  ) {
        console.log(rows[i]);
    }return rows;
}
createArray(5);

CodePudding user response:

You need to create an array and return it, whereas you return just rows which is a number. The idea of using a for loop is the best way to go. In that loop you just need to set the values in the array accordinlgy. Another problem in your code is that rows is of type number and does have a property length but that does not have the desired value. So we just use rows in the for loop. We start the loop with i = 0 because array indices start at 0.

Code

function createArray(rows) {
  let arr = new Array(rows);
  for (let i = 0; i < rows; i  ) {
    arr[i] = i   1;
  }
  
  return arr;
}

console.log(createArray(5));

CodePudding user response:

We can not use length property for number. create an empty array and then push values into that array until required size is achieved.

function createArray(rows) {
    var arr = [];
    for(let i = 1; i <= rows; i  ) {
        arr.push(i);
    }return arr;
}
createArray(5);

CodePudding user response:

I think what you want is createArray(5) return [1,2,3,4,5] if that's the case you could do this

function createArray(rows) {
    const arr = []
    for(let i = 1; i <= rows; i  ) {
        arr.push(i);
    }
    return arr;
}
console.log(createArray(5));

CodePudding user response:

The problem is, that rows.length is not available on 5, because 5 is a number.

You have to use an array as parameter:

Array(5) creates an array with the length of 5 and fill("hello") fills this array with "hello" values.

function createArray(rows) {
  for (let i = 1; i < rows.length; i  ) {
    console.log(rows[i]);
  }
  return rows;
}

const rows = Array(5).fill("hello");

createArray(rows);

I don't know, if this is the behaviour you want, if not, I misunderstood your question.

  • Related