开发者

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 ne开发者_运维技巧w 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';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜