Sorry if the title of this post is a bit confusing.
Here’s the problem:
I’m converting a string into an array using split(' ')
.
Then I’m removing the first letter of the new array using .splice(0,1)
.
This is then output to the screen.
HTML:
<button onclick="arraySplice()">
Remove first item from Array with .splice(0, 1)
</button>
<p id="array-splice"></p>
JAVASCRIPT:
const fruitsString = "Banana";
If I write the function this way I get the desired result: first letter is removed and the rest of the
array is printed -
function arraySplice() {
const newFruitsSplicedArray = fruitsString.split('')
newFruitsSplicedArray.splice(0,1);
const output = document.getElementById("array-splice");
output.innerHTML = newFruitsSplicedArray;
}
Screen: a,n,a,n,a
Console: ["a", "n", "a", "n", "a"]
But, if I write the function like this I get the opposite result - everything but the first letter is removed.
function arraySplice() {
const newFruitsSplicedArray = fruitsString.split('')
const arrSplice = newFruitsSplicedArray.splice(0,1);
const output = document.getElementById("array-splice");
output.innerHTML = arrSplice;
console.log(arrSplice)
}
I get:
Screen: B
Console: ["B"]
Could anyone explain why this is happening?