Aarav Shah
Aarav Shah

Reputation: 85

Is there a method that allows me to print an array without the commas?

I have the following code in JavaScript:

let calculationsArray = [];
$('.number-1').on('click', ()=> {
  calculationsArray.push(1);
  document.getElementById('screen-text').innerHTML = calculationsArray;
})
$('.number-2').on('click', ()=> {
  calculationsArray.push(2);
  document.getElementById('screen-text').innerHTML = calculationsArray;
})

And the following code in HTML:

<span id='screen-text'></span>

But when the code runs, it prints like this: 1,2. Is there a way to print the array so it shows up without commas, like this: 12? I know a way to do it is to replace calculationsArray after innerHTML with the number specified but when I try that, it replaces the number before. For example, if I replace calculationsArray, and I press the 1 button and 2 button, it starts like this: 1, but after I press the 2 button, it replaces the 1 with 2 like this: 2. I want it to append the 2 after the 1, like so: 12.

Upvotes: 1

Views: 456

Answers (3)

user8897421
user8897421

Reputation:

As others mentioned, you can use .join() with whatever string you want as the separator.

But also, you don't need repetitive code like that. Just select all the elements, give them the same handler, and extract the number from the class name.

let calculationsArray = [];
$('[class*=number-]').on('click', (event)=> {
  const n = +event.currentTarget.className.match(/\bnumber-(\d+)\b/)[1];
  calculationsArray.push(n);
  document.getElementById('screen-text').innerHTML = calculationsArray.join("");
});

Upvotes: 0

Abid Nawaz
Abid Nawaz

Reputation: 956

Here you are.

let calculationsArray = [];
$('.number-1').on('click', () => {
  calculationsArray.push(1);
  document.getElementById('screen-text').innerHTML =calculationsArray.join('');
})
$('.number-2').on('click', () => {
  calculationsArray.push(2);
  document.getElementById('screen-text').innerHTML =calculationsArray.join('');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='screen-text'></span>
<button class="number-1">1</button>
<button class="number-2">2</button>

Upvotes: 0

You can use join try this:

calculationsArray.join("")

Upvotes: 2

Related Questions