拼接在循环中调用时不删除元素 [英] splice not removing elements when called in a loop

查看:35
本文介绍了拼接在循环中调用时不删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个代码,该代码接受一个输入字符串和一组标记,并从标记到找到标记的末尾删除所有内容.我有一个识别标记的函数,然后找到它所在的行的结尾.此函数返回一个数组,其中每对元素从0开始对应于我要拼接的部分.但是,只有我对拼接的一些调用实际上删除了所有内容.

这是我的主要代码:

 功能解决方案(输入,标记){变量位置=标识(输入,标记);var arr = input.split('');for(var i = 0; i< positions.length; i + = 2){arr.splice(positions [i],positions [i + 1]-positions [i]);console.log(positions [i + 1]);}返回arr.join('');} 

我已经测试过识别,它正在返回我期望的结果.这是我目前未通过的测试:

  Test.assertEquals(solution(苹果,梨#和香蕉\ ngrapes \ nbananas!apples",[#",!"]),苹果,梨\ ngrapes \ nbananas") 

我对identify()的调用结果为[14,27,43,50],我尝试直接与(43,7)进行拼接,该方法可以正常工作,因此我无法弄清楚为什么它没有删除任何元素同时在循环中使用.结果我总是这样:

预期:苹果,梨葡萄香蕉

取而代之的是:苹果,梨葡萄香蕉!苹果

解决方案

您需要向后遍历 positions 数组,因为当您拼接出 arr 的某些元素时,这些元素之后的所有内容的索引都会更改.

 功能解决方案(输入,标记){变量位置=标识(输入,标记);var arr = input.split('');for(var i = positions.length-2; i> = 0; i- = 2){arr.splice(positions [i],positions [i + 1]-positions [i]);console.log(positions [i + 1]);}返回arr.join('');} 

I am writing a code which takes an input string and an array of markers and removes everything from the markers to the end of the on which it is found. I have a function which identifies a marker and then finds the end of the line it is on. This function returns an array where each pair of elements, starting with 0, corresponds to a section I would like to splice. However, only some of my calls to splice are actually removing anything.

Here is my main code:

function solution(input, markers){
  var positions = identify(input, markers);
  var arr = input.split('');

  for(var i = 0; i<positions.length; i+=2){
    arr.splice(positions[i], positions[i+1] - positions[i]);
    console.log(positions[i+1]);
  }
  return arr.join('');
}

I have tested identify and it is returning what I expect. This is the test I am currently failing:

Test.assertEquals(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]), "apples, pears\ngrapes\nbananas")

The result of my call to identify() is [14,27,43,50] and I have tried splicing with (43, 7) directly which works, so I can't figure out why it's not removing any elements while being used in the loop. I always get this as a result:

Expected: apples, pears grapes bananas

instead got: apples, pears grapes bananas !apples

解决方案

You need to work backwards through the positions array, because when you splice out some elements of arr, the indexes of everything after those elements change.

function solution(input, markers){
  var positions = identify(input, markers);
  var arr = input.split('');

  for(var i = positions.length-2; i >= 0; i-=2){
    arr.splice(positions[i], positions[i+1] - positions[i]);
    console.log(positions[i+1]);
  }
  return arr.join('');
}

这篇关于拼接在循环中调用时不删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆