简体   繁体   中英

Insert an element at each index - Vanilla JS

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"]

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>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM