简体   繁体   English

使用 splice 方法添加元素

[英]Adding element with the splice method

I am trying to Us the javascript splice method to add a "-" before every capital latter in my array but it is not working.我正在尝试使用 javascript splice 方法在我的数组中的每个大写字母之前添加一个“-”,但它不起作用。 I don't know what I am doing wrong.我不知道我做错了什么。 Here is my code below.下面是我的代码。

function spinalCase(str) {
  let strArr = [];
  for(let i = 0; i < str.length; i++){
    strArr.push(str[i]);
  }
  for(let i = 0; i < strArr.length; i++){
    if(strArr[i] !== strArr[i].toLowerCase()){
      strArr.splice(strArr.indexOf(strArr[i]),0, "-");
    }
  } 
console.log(strArr);
}

spinalCase('thisIsSpinalTap');

When you add a new element with splice you're increasing the length of the array and the loop is never able to finish.当您使用splice添加新元素时,您会增加数组的length ,并且循环永远无法完成。 If you work the loop from the end of the array to the beginning instead you can avoid this problem.如果您从数组末尾到开头处理循环,则可以避免此问题。

 function spinalCase(str) { let strArr = []; for (let i = 0; i < str.length; i++) { strArr.push(str[i]); } // Work the loop from the end to the beginning for (let i = strArr.length - 1; i >= 0 ; i--) { if (strArr[i] !== strArr[i].toLowerCase()) { strArr.splice(strArr.indexOf(strArr[i]), 0, "-"); } } console.log(strArr.join('')); } spinalCase('thisIsSpinalTap');

I know you wanted to use splice, but here is a little regex solution;我知道你想使用 splice,但这里有一个小的正则表达式解决方案; just in case.以防万一。

 function spinalCase(str) { return str.replace(/[AZ]/g, "-$&").toLowerCase(); } console.log(spinalCase("thisIsSpinalTap")) // this-is-spinal-tap

You changed your array when you do:您在执行以下操作时更改了数组:

strArr.splice(strArr.indexOf(strArr[i]),0, "-");

So strArr.length is not constant for the loop for(let i = 0; i < strArr.length; i++)所以strArr.length对于循环for(let i = 0; i < strArr.length; i++)不是常数

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

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