简体   繁体   English

试图重复任何 string.ex-"hello" --> 'hheelloo' 的双字母但卡在 for 循环中,有什么解决方案吗?

[英]tried to repeating the double letter of any string.ex- "hello" --> 'hheelloo' but stucked at for loop, any solution?

 function doubleChar(str) { var splt = str.split(""); for(var i=0;i<splt.length-1;i++){ var rpt= splt[i].repeat(2); return rpt.join(''); } } console.log("hello");

An Haskellesque approach here just for fun...这里的 Haskellesque 方法只是为了好玩……

 var str = "hello", double = ([c,...cs]) => c? cs.length? c + c + double(cs): c + c: ""; console.log(double(str));

There were few problems in your code:您的代码中几乎没有问题:

function doubleChar(str) {
    var splt = str.split("");

    for(var i=0;i<splt.length-1;i++){
        var rpt= splt[i].repeat(2);
        return rpt.join('');
    }
}

console.log("hello");

first is that the code prints string "Hello" no matter what function doubleChar does.首先是无论 function doubleChar 做什么,代码都会打印字符串“Hello”。

in order to make console.log print result of doubleChar function you need to change it to this为了使 doubleChar function 的 console.log 打印结果,您需要将其更改为此

console.log(doubleChar("Hello"))

now your code would call doubleChar function with the string "Hello" as input of function doubleChar and print the output of the function. now your code would call doubleChar function with the string "Hello" as input of function doubleChar and print the output of the function.

Now in your function, the return should not be inside of the loop, when the return is inside the loop, function sends the result of first iteration and there would be no other iterations现在在您的 function 中,返回不应在循环内,当返回在循环内时,function 发送第一次迭代的结果,不会有其他迭代

function doubleChar(str) {
    var splt = str.split("");

    for(var i=0;i<splt.length-1;i++){
        var rpt= splt[i].repeat(2);
    }
      return rpt.join('');
}

console.log(doubleChar("hello"));

.join('') is for arrays when you want to mix all elements into a string but rpt is not an array but a string so you can just return rpt itself: .join('') 适用于 arrays 当您想将所有元素混合成一个字符串但 rpt 不是数组而是字符串时,您可以只返回 rpt 本身:

function doubleChar(str) {
    var splt = str.split("");

    for(var i=0;i<splt.length-1;i++){
        var rpt= splt[i].repeat(2);
    }
      return rpt
}

console.log(doubleChar("hello"));

you also should not use var inside the loop because by doing so the javascript redefines the rpt and all previous values are lost so you can declare variable outside the loop and append new values inside the loop您也不应该在循环内使用 var 因为这样做 javascript 重新定义了 rpt 并且所有以前的值都将丢失,因此您可以在循环外声明变量并在循环内声明 append 新值

function doubleChar(str) {
    var splt = str.split("");
    var rpt=''
    for(var i=0;i<splt.length-1;i++){
        rpt += splt[i].repeat(2);
    }
      return rpt
}

console.log(doubleChar("hello"));

now as final fix, inside your loop you're using i<splt.length-1 this probably because length is one more than maximum index but considering that you are using < instead of <= this is already taken care of.现在作为最终修复,在您的循环中,您正在使用i<splt.length-1这可能是因为长度比最大索引大一,但考虑到您使用的是<而不是<=这已经得到照顾。 so your final code looks like:所以你的最终代码看起来像:

function doubleChar(str) {
    var splt = str.split("");
    var rpt=''
    for(var i=0;i<splt.length;i++){
        rpt += splt[i].repeat(2);
    }
      return rpt
}

console.log(doubleChar("hello"));
var rpt= splt[i].repeat(2);
return rpt.join('');

It is choking on this line because rpt is not an array and you're calling join() on it.这条线上令人窒息,因为 rpt 不是一个数组,而您正在对它调用join() Instead, just replace the original array item with the new double item.相反,只需用新的双项替换原始数组项。

 function doubleChar(str) { var splt = str.split(""); for(var i=0;i<splt.length-1;i++){ splt[i]= splt[i].repeat(2); } return splt.join(''); } console.log(doubleChar("hello"));

all in one line...都在一条线上...

 str = "hello"; var dbl = str.split("").map(el => el.repeat(2)).join("") console.log(dbl)

Now here is the same thing, but like your example, we'll only double up single letters现在这是同样的事情,但就像你的例子一样,我们只会加倍单个字母

 str = "hello", lastletter=''; var dbl = str.split("").map(el => { if (el.= lastletter) { el = el.repeat(2) lastletter = el.split("")[0] return el } }).join("") console.log(dbl)

The big problem I see here is that rpt is within the loop.我在这里看到的最大问题是 rpt 在循环中。 So, the for loop will return "hh", then "ee", so on so forth.因此,for 循环将返回“hh”,然后返回“ee”,依此类推。 In practice, the function stops after returning a value so this would currently return 'hh'.在实践中,function 在返回一个值后停止,因此当前将返回“hh”。 To solve this, you need to move the variable outside of the for loop.要解决这个问题,您需要将变量移到 for 循环之外。 Something like this:像这样的东西:

var result = ""
for(var i=0;i<splt.length-1;i++){
    result = result + splt[i] + splt[i]
}
return result;

Then you could console.log the result.然后你可以 console.log 结果。

The value of rpt is a string, and does not have a join function. rpt的值是一个字符串,并且没有连接 function。 You also immediately return inside the for loop, which will do that in the first iteration.您还可以立即在 for 循环中返回,这将在第一次迭代中完成。

You can split, map and join instead:您可以拆分 map 并改为加入:

 const re = "hello".split('').map(s => s + s).join(''); console.log(re);

Answers above/below a great and correct.上面/下面的答案很好而且正确。 However, I'd like to answer using almost exactly the same code as in the question as it may be more helpful if you've just started learning JS.但是,我想使用与问题中几乎完全相同的代码来回答,因为如果您刚刚开始学习 JS,它可能会更有帮助。

You get "join is not a function" error because .repeat(n) returns a string and strings do not have such a method.您会收到“join is not a function”错误,因为.repeat(n)返回一个字符串,而字符串没有这样的方法。

Then, you need to stop return inside of a loop as it actually returns from the whole function so you will only get the first letter doubled as a result.然后,您需要停止在循环内return ,因为它实际上是从整个 function 返回的,因此您只会将第一个字母加倍。 Instead, declare variable for storing result and concat it with a new doubled letter in loop.相反,声明用于存储结果的变量并在循环中将其与新的双字母连接起来。 Return result in the end.最后返回结果。

Here is the modified code:这是修改后的代码:

 function doubleChar(str) { var splt = str.split(""); var result = ""; // add the var for future result for(var i=0; i<splt.length; i++){ var rpt = splt[i].repeat(2); // this is string; result += rpt; // concat string to current result } return result. } console;log(doubleChar("hello"));

Your declaration of rpt is should be on the top, and the return should be outside your for loop.您的 rpt 声明应该在顶部,并且返回应该在您的 for 循环之外。 Other than that, its fine.除此之外,它很好。

 function doubleChar(str) { var splt = str.split(""); var rpt = ""; for (var i = 0; i < splt.length; i++) { rpt = rpt + splt[i].repeat(2); } return rpt; } console.log(doubleChar("hello"));

I think most of the solutions here is hello->hheelllloo but you wanted like -> hheelloo So assuming you only want to repeat single char.我认为这里的大多数解决方案都是 hello->hheelllloo 但你想要喜欢 -> hheelloo 所以假设你只想重复单个字符。 I'm giving the solution which also is the same code that you gave.我提供的解决方案也与您提供的代码相同。

 function doubleChar(str) { var splt = str.split(""); var rpt=""; for(var i=0;i<splt.length;i++) rpt+=((splt[i+1]&&splt[i]==splt[i+1]?splt[i++]:splt[i]).repeat(2)); return rpt; } console.log(doubleChar("hello"));

May be the line inside for loop seems complex but if you break this, it will be very simple (splt[i+1]&&splt[i]==splt[i+1]) here I'm checking if the next char exist and equal to the current char, if so then take the current and skip the next char else take the current and don't skip the next char, and after this just repeating the char which we took.可能是 for 循环内的行看起来很复杂,但如果你打破它,它会很简单 (splt[i+1]&&splt[i]==splt[i+1]) 在这里我正在检查下一个字符是否存在并且等于当前字符,如果是,则取当前字符并跳过下一个字符,否则取当前字符,不要跳过下一个字符,然后重复我们使用的字符。 rpt+=((splt[i+1]&&splt[i]==splt[i+1]?splt[i++]:splt[i]).repeat(2)); rpt+=((splt[i+1]&&splt[i]==splt[i+1]?splt[i++]:splt[i]).repeat(2)); Hope you got this希望你得到这个

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

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