简体   繁体   中英

Javascript append an element to Array at specific index

I have a dynamically generated Array:

myArr = ["val0a", "val1a", "val2a"... "val600a"]

I am having problems appending a new array values to this array in a loop. My Array should look like this after the append:

myArr = ["val0a", "val1a val1b", "val2a val2b"... "val600a"]

Please note that the new array and the old one do not have the same length.

How can I do this? It have to be something simple but I can't figure it out.

You can write a function along the lines of this:

Array.prototype.appendStringToElementAtIndex = function(index, str) {
    if(typeof this[index] === 'undefined' || typeof this[index] !== 'string') return false;
    this[index] += ' ' + str;
};


myArr = ["val0a", "val1a", "val2a"];
myArr.appendStringToElementAtIndex(1, "val1b");

console.log(myArr.join(', ')); //val0a, val1a val1b, val2a
myArr.push(myArr[myArr.length - 1].split(" ").push("val42").join(" "));  // even

to append a value to an element of an array you can just do this:

myArr = ["val0a", "val1a", "val2a"... "val600a"];
indexToAppendTo = 2;
val2 = "val2b"
myArr[ indexToAppendTo ] += (" " + val2) ;

To concatenate to an element that's a string:

myArr[2] = myArr[2] += 'blah';

To reassign it:

myArr[2] = 'foo';

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