简体   繁体   English

使用拼接方法将多个元素插入数组

[英]Insert multiple elements into array with splice method

I have a problem I'm trying to solve.我有一个我正在尝试解决的问题。 I am trying to insert a space where ever there is a instance of a capital letter.我试图在有大写字母实例的地方插入一个空格。 The problem is that the space is pushed into the correct index but for all other instances where a capital letter appears, it doesn't apply that space.问题是该空间被推入正确的索引,但对于所有其他出现大写字母的情况,它不会应用该空间。 I have researched extensively about the splice methods but could not figure out a solution to my problem.我对拼接方法进行了广泛的研究,但无法找到解决问题的方法。 Can someone point me in the right direction.有人可以指出我正确的方向。

function solution(string) {
  
  let splitStr = [...string];
  
  
  for(let i = 0; i < splitStr.length; i++) {
    
    if(!splitStr[i].toUpperCase()) return
    
    if(splitStr[i] === splitStr[i].toUpperCase()) {
        let indexOfCapLetter = splitStr.indexOf(splitStr[i].toUpperCase());
        splitStr.splice(indexOfCapLetter, 0, ' ' );
        
        return splitStr
      }
    
  }
  
 
}

First issue is that you're returning the array inside your if statement within the loop.第一个问题是您在循环中的 if 语句中返回数组。 This escapes the function after the first capital letter.这在第一个大写字母之后转义了 function。 But after that there's another issue.但在那之后还有另一个问题。

Whenever you add a new element to the array, the characters after it are moved to a higher index.每当您向数组添加新元素时,它后面的字符都会移动到更高的索引。

To counter this you can loop through the array backwards so the affected elements are always ones you've already parsed:为了解决这个问题,您可以向后循环数组,以便受影响的元素始终是您已经解析过的元素:

 function solution(string) { let splitStr = [...string]; for(let i = splitStr.length-1; i >=0; i--) { if(splitStr[i] === splitStr[i].toUpperCase()) { splitStr.splice(i, 0, ' ' ); } } return splitStr.join(''); } console.log(solution('HelloWorldLongString'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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