加入数组的一部分,其余部分保留在Javascript中

时间:2016-10-02 18:58:45

标签: javascript

我有一个数组,我想从一些beginIndex加入一些endIndex,剩下的就是原样。

例如,我有这个数组:

['first', 'second', '<error>', 'Can not parse the third element', '</error>', 'fourth', 'fifth']

我想join('\n')从索引2到索引4的元素。所以我得到:

['first', 'second', '<error>\nCan not parse the third element\n</error>', 'fourth', 'fifth']

有什么建议吗?

编辑:哇,感谢这个无辜的精心制作的问题的4个downvotes和2个选票。是的,我得到了一些与循环有关的东西,但我发现它很难看,我正在寻找更优雅的东西,我不知道拼接方法。感谢Soviut和Nina的有趣答案。希望有同样问题的其他人也可以从中学习......

3 个答案:

答案 0 :(得分:1)

您可以使用slice获取数组的子集,加入它们,然后splice将这些值重新放回数组中。拼接允许在您同时插入时删除/替换元素。

&#13;
&#13;
var logs = ['first', 'second', '<error>', 'Can not parse the third element', '</error>', 'fourth', 'fifth'];

var startIndex = 2;
var endIndex = 5;

var slicedTokens = logs.slice(startIndex, 5);
var joinedString = slicedTokens.join('');
var deleteCount = endIndex - startIndex;

logs.splice(startIndex, deleteCount, joinedString);

console.log(logs);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用Array#splice

  

splice() 方法通过删除现有元素和/或添加新元素来更改数组的内容。

&#13;
&#13;
var array = ['first', 'second', '<error>', 'Can not parse the third element', '</error>', 'fourth', 'fifth'],
    beginIndex =2,
    endIndex = 4;

array.splice(beginIndex, 0, array.splice(beginIndex, endIndex - beginIndex + 1).join('\n'));

console.log(array);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

一种简单的方法是: -

public void aFunction() {
  if(a == b) {
   // Do something...
   return; // stop here
  }
  // Do something else
}