2

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>
    );
};
3
  • I tried this and it seem to work fine. What specifically is the issue? I don't know what "doesn't take range as correct parameter" means. Show your current output and your desired output Commented Oct 26, 2020 at 8:06
  • When I log a it prints as null array. Commented Oct 26, 2020 at 8:12
  • 1
    change const a=Array(...Array(range).keys()); to const a=Array(...Array(parseInt(range)).keys()); Commented Oct 26, 2020 at 8:23

3 Answers 3

1

Actually what I did was

const a = Array(...Array(parseint(range)).keys());
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.