简体   繁体   English

使用拼接Java脚本在数组中增量添加元素

[英]Adding Elements in An Array Incrementally Using Splice Javascript

I'm trying to add "-" before capital letters. 我正在尝试在大写字母前添加“-”。 eg helloWorld becomes hello-world. 例如helloWorld成为hello-world。

My code, however, is placing the "-" in the array at the wrong places. 但是,我的代码将数组中的“-”放在错误的位置。 ie thisIsSpinalTap becomes this-I-sSpin-alTap 即thisIsSpinalTap变为this-Isspin-alTap

What's wrong with my code? 我的代码有什么问题?

function spinalCase(str){
str = str.replace(/ /g,'-');
strArr = str.split("");
for(i=1;i<str.length;i++){
    if(str.charAt(i)==str.charAt(i).toUpperCase()&&str.charAt(i)!=="-"){
        console.log(i);
        strArr.splice(i,0,"-");
    }
} 
return strArr.join("");
}

spinalCase('thisIsSpinalTap'); // returns this-I-sSpin-alTap 

What's wrong is that every time you do a splice, strArr drifts to the left; 出问题的是,每次您进行拼接时, strArr漂移。 so ideally you should keep another counter that starts at 0 and increases whenever you do another splice, eg: 因此,理想情况下,您应该保留另一个计数器,该计数器从0开始并在每次执行其他拼接时增加,例如:

var k = 0;
// ...
    strArr.splice(i + k, 0, '-');
    ++k;

Assuming you're not just doing this to exercise, this is a much easier way: 假设您不只是为了锻炼而已,这是一种更简单的方法:

var s = 'thisIsSpinalTap';

var res = s.replace(/([a-z])([A-Z])/g, '$1-$2'); // "this-Is-Spinal-Tap"

The expression matches a lowercase letter followed by an uppercase letter and then replaces it with a dash in between. 该表达式先匹配一个小写字母,再匹配一个大写字母,然后用中间的破折号代替它。

The problem here is you are modifying the array in the loop, but you are checking the characters using the string which is not updated based on the new character insertions that happens in the array, so when a - is inserted the indexes in the string will be 1 less that that of the array that is why the - are inserted 1 position less than what is required in the second instance. 这里的问题是您正在循环中修改数组,但是您正在使用字符串检查字符,该字符串不会根据数组中发生的新字符插入而更新,因此当插入-时,字符串中的索引将比数组少1,这就是为什么-插入的位置比第二个实例少1个位置的原因。 The same pattern will continue for each insertion so the 3rd insertion will happen at postion-2 每次插入将继续相同的模式,因此第3次插入将发生在postion-2

 function spinalCase(str) { str = str.replace(/ /g, '-'); var strArr = str.split(""), i, code; for (i = 1; i < str.length; i++) { //since we are modifying the array the indexes in the original array can't be used code = strArr[i].charCodeAt(0); if (code >= 65 && code <= 90) { strArr.splice(i, 0, "-"); //since we are inserting a new element before current element we need to skip an extra element i++; } } return strArr.join(""); } var result = spinalCase('thisIsSpinalTap'); snippet.log(result) 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

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

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