SpinalTap need help

SpinalTap need help
0

#1

Ive simplified code a bit to narrow the issue.
In this fiddle https://jsfiddle.net/htzLe0wt/ I target all lowercase p in array. They targeted correctly, condition evaluates true twice and we have splice doing change twice too. This is an intention, everything alrgiht.

However when i set parameter of splice howmany to 0 i have a problem. https://jsfiddle.net/htzLe0wt/2
By documentation the only difference that should be is that i add new letter without replacing (item).
So i expect that i will have something like this
thisissp inaltap .

However code gives very different output.

  1. First problem it doesnt do changes at respective positions of ‘p’ - like in first fiddle. As seen in https://jsfiddle.net/htzLe0wt/2 change will occur ALL IN ONE PLACE. At ‘first stop’, at first lowercase p.

  2. Change will not occur twice (which we expect from testing splice with our first fiddle with THE VERY SAME CONDITION) it will occure 8 times.

So why is setting parameter howmany of splice to 0 in this situation giving this strange output when the only difference with first fiddle should be that it adds things without removing items?


#2

While I have done the challenge with this ugly hack https://jsfiddle.net/htzLe0wt/6/ the question in hand still holds.


#3

The way you’re using splice(), you’re inserting a space at the index you’re currently working on. Think about what that means:

“This is spinal tap”

  • Character at index 7 == “p”
  • Insert a space at current index per your parameters here arr0.splice(index, 0, ' ')
  • Character at index 7 is now a space, everything is shifted forward by one
  • Loop moves on to the next index, 8, which now === “p”

The second “p” doesn’t change because the loop quits at index 15, the size of the original array.


#4

I see. So when we worked with replacements our so-called ‘index-layout’ was not touched, but with 0 parameter index-layout is shifted to stretch for new guests…Never would have guessed on my own, had no even slightest idea this might have been happening under the table. Thank you very much.