Home > OS >  getting extra value in JS array
getting extra value in JS array

Time:11-16

I want to create from user input two arrays while calling a function. The issue is that I get an extra value in the array that I did not type in; it’s looks like a default value...

I have the following code:

const NameArr = [];
const IdArr = [];

function getName() {
  const Input = document.getElementById("input").value;
  const list_names = Input.split(", ");

  for (let i of list_names) {
    NameArr.push(i);
    IdArr.push(i);
  };
  console.log(NameArr, IdArr);
  return NameArr, IdArr;
};

getName();
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script src="main.js" charset="utf-8" defer></script>
    <title></title>
  </head>
  <body>
    <form id="form" action="#" method="post">
      <input type="text" id="input">
      <button onclick="getName();">Get Data</button>
    </form>
  </body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I am not sure why I get an extra value [""] in my arrays...

CodePudding user response:

You are calling getName() at the end of your code.

Inbside getName you are getting the value of your input field which is initially the empty string ""

const Input = document.getElementById("input").value;

Then you are using the push() method which will push the empty string at first and now this is the content of your array

[""]

Later when you add other values and call getName() you will add the values on top of the already existing value

[""]

CodePudding user response:

Answer based on the comments.

the function call getName() at the end of the script calls the function right after it, even when the button hasn’t been pressed by the user. Therefore, it adds the empty value in the array since there is an empty value.

Just need to remove the getName().

const NameArr = [];
const IdArr = [];
Dict = {};

function getName() {
  const Input = document.getElementById("input").value;
  const list_names = Input.split(", ");

  for (let i of list_names) {
    NameArr.push(i);
    IdArr.push(i);
  };
  console.log(NameArr, IdArr);
};
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script src="main.js" charset="utf-8" defer></script>
    <title></title>
  </head>
  <body>
    <form id="form" action="#" method="post">
      <input type="text" id="input">
      <button onclick="getName();">Get Data</button>
    </form>
  </body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related