2016-10-02 78 views
-4

我有一个数组,我想从某个beginIndex加入某个endIndex,并保持原样。加入数组的一部分,并将其余部分保留为Javascript

例如,我有这样的数组:

['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提供有趣的答案。希望其他具有相同问题的人也可以从中学习...

+5

我的建议是:“发表您尝试在你的问题,说明在何处以及如何失败“。你的尝试做错了什么,他们做了什么,他们不应该做什么,他们做了什么,他们应该做什么?您的控制台中是否有任何错误(大多数浏览器中的F12)?请在你的问题中发布你的“* [mcve] *”。 –

+0

看来你可以做“获得元素2到4的子阵列,加入它们,并用单一结果替换原来的元素2到4”。所以下一步就是打开文档并找到实现这个功能的函数,然后将它们串联起来,形成一个尝试的解决方案。 – Jon

+0

@DavidThomas我觉得我的企图只会给读者带来同样问题的噪音。我正在使用for循环,这工作,之后,我尝试了一下reduce方法,它的工作方式很好,但不像我认为的那样优雅。我不知道拼接方法,这似乎是解决这个问题最优雅的方法。 – Kasper

回答

1

你可以使用Array#splice

splice()方法通过去除现有元件和/或添加新元素改变阵列的内容。

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);

1

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

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);

1

一个简单的方法来做到这一点是: -

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

var b = []; 
var startJoinIndex = 2; 
var endJoinIndex = 4; 
var joinedValue = ""; 
a.forEach(function(item, index){ 
    if (index >= startJoinIndex && index <= endJoinIndex){ 
    joinedValue += item; 
    if (index === endJoinIndex){ 
     b.push(joinedValue); 
    } 
    } else { 
    b.push(item); 
    } 
}); 

console.log(b); 
相关问题