So I have an array that I want to loop through, and at each index I want to insert a string.
I based my loop on the below code, hoping it would work. But each time it breaks my browser, any idea why this is?
//code works fine
var array = ['a', 'b', 'c'];
i = 0;
while (i <= array.length) {
array.splice(i, 0, 0);
i += 2;
}
console.log(array);
<h4>slappin' and pampering the modern way</h4>
//problematic code
function get_nodes() {
let el = document.querySelector("h4");
let childnods = el.innerText;
let newArray = childnods.split(' ');
let i = 0;
while (i <= newArray.length) {
newArray.splice(i, 0, 'test');
i += 2;
}
console.log(newArray);
}
get_nodes()
Expected result would be:
newArray = ["test", "slappin'", "test", "and", "test", "pampering", "test", "the", "test", "modern","test", "way", "test"]