Home > OS >  using shift() brings back the first one every time (javascript)
using shift() brings back the first one every time (javascript)

Time:04-04

I have a function that searches for everytime ';' is found inside a textarea and makes it into a array. See the code below.

    function compile() {
        // Sets the variable for every line
        var compileLineCount = document.getElementById('devInput').value.split(';');
        for (let i = 0; i < compileLineCount.length; i  ) {
            console.log(document.getElementById('devInput').value.split(';').shift(i))
            console.log(i)
          }
    
    }

But whenever I run the function, it shows the first one every time.

screenshot of console log when i run the function

Anyone know how to fix this? Help would be very appreciated.

CodePudding user response:

I figured out what I did wrong. I forgot shift() also removes the item from the array.

I changed it from .shift(i) to [i].

Thank you jsn00b for the link to the docs

CodePudding user response:

Your shift() method is used incorrectly. According to MDN, it states:

The shift() method removes the first element from an array and returns that removed element.

So, the shift() method doesn't take any parameters. This is why your code isn't working.


To fix this issue, you can get the index from the array using [i], like so.

document.getElementById("devInput").value.split(";")[i];

The only difference in that line is that .shift() is replaced with [i], which gets the element in the array at that specific index.

CodePudding user response:

As per the official shift() document.

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

Hence, It should be like :

var compileLineCount = document.getElementById('devInput').innerHTML.split(';');
for (let i = 0; i <= compileLineCount.length; i  ) {
  const splittedValue = compileLineCount.shift(i)
  console.log(splittedValue)
  console.log(i)
}
<p id="devInput">
Hello my name is alpha;Age is 30;I love to help
</p>

  • Related