1

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"]
2
  • What is your expected output? Can you explain bit more on it?? Commented Feb 15, 2021 at 7:51
  • added the expected result, thanks for the heads-up! Commented Feb 15, 2021 at 7:57

3 Answers 3

3

Actually you have written the correct code for the expected output, just you need to replace the array.splice(i, 0, 'test'); to newArray.splice(i, 0, 'test'); in your while loop.

Sign up to request clarification or add additional context in comments.

3 Comments

I did that, and my browser is still breaking. I still would like to find out why that is.
Is there any console error or you are not getting proper output?
I don't get any output in the console. The browser seems to go into an infinite loop.
3

You can split your string on space and use array#flatMap to add test word after each word.

const statement = document.querySelector("h4").innerText,
      result = statement.split(' ').flatMap(word => [word, 'test']),
      output = ['test'].concat(result);

console.log(output);
<h4>slappin' and pampering the modern way</h4>

Comments

1

What about :

let el = document.querySelector("h4");
let childnods = el.innerText;
let arrayOfItems = childnods.split(' ');

console.log(arrayOfItems);

let newString = arrayOfItems.join(",test,");

let newArray = newString.split(',');


console.log(newArray);
<h4>slappin' and pampering the modern way</h4>

Make sure that you don't have , in your original text .

Then you may add test as the first and last items .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.