Creating dynamic array in react js

I'm trying to create an array dynamically by getting user input. range comes as a parameter. When I try to console.log() that it logs the correct value of range, but when I try to use it in const a=Array(...Array(range).keys()); it doesn't take range as correct parameter. When I hard code a number instead of range it gives a correct array. What would be the problem here??

import React from 'react';
import { Button, TextField } from '@material-ui/core';
import { useState } from 'react';

export default  function handleSumOfMultipliers(multiplier, range) {
    console.log("range" + range)
    
    const a = Array(...Array(range).keys());
    console.log(a);

    return (
        <div></div>
    );
};

Upvotes: 2

Views: 3121

Answers (3)

Actually what I did was

const a = Array(...Array(parseint(range)).keys());

Upvotes: 1

ahg
ahg

Reputation: 89

Make sure you are casting the 'range' value to an int. If I do this:

var a = Array('6')
a.length

We get 1 as the array length. User input is usually a string so maybe that's your mistake.

Upvotes: 0

Jayce444
Jayce444

Reputation: 9063

I'm guessing you're forgetting to pass in a first argument, since you aren't using it in the function at the moment. So given your current function definition, if you call handleSumOfMultipliers(5) then inside the function, multiplier is 5 and range is undefined.

You need to given a dummy argument for the first parameter, so handleSumOfMultipliers(null, 5). That way range will be 5 and it should work just fine

Upvotes: 0

Related Questions