繁体   English   中英

用.length在Javascript中重复一个函数

[英]Repeat a function in Javascript with .length

我有一长串。

var string = "This is a long string."

我还具有将字符串下载到“路径”的功能。

downloadfunction{... 'echo "'+string+'" >> '+path;}

如何对字符串的每2个字母执行此功能? 阅读有关使用“ .length”的内容,但不确定在这种情况下如何实现。 我也不想将字符串拆分为数组。 下载功能应有助于分割字符串以逐步下载2个字母。

即我想一次下载字符串2个字母。

编辑:为澄清起见,该字符串需要一次下载x个字符,因为如果超出该限制,下载将中断。

这是一个有关如何执行此操作的示例:

var string = 'a really really really long string \
    that I want to split by two letters at a time';

// this needs to be ceiling so that it always rounds up on odd numbers
// otherwise the last letter may be left out
var iterations = Math.ceil(string.length / 2);

for (var i = 0; i < iterations; i++) {

    // we are iterating over half of the length but want to go two letters at a time
    var j = i*2;

    // make a new string with the first letter
    var letters = string[j]

    // this is an if statement to check if there is a second letter
    // if there is concat it to the first letter
    // otherwise the last set of an odd length would concat `undefined` to it
    if (string[j+1]) { letters += string[j+1]; }

    // call your function here passing `letters` to it
    downloadfunction{... 'echo "' + letters + '" >> '+path;}
}

计算字符串长度除以2向上或向下取整

然后在除法后对金额进行for循环。

像这样的东西

//Your string that is downloaded
var string = "This is a long string."

//calculate the amount of character in the string
var amount = string.length;

//divide the string by 2
var roundnr = amount/2;

for (var i=0;i<Math.round(roundnr);i++)
{ 
//do something here for every 2 characters in the string
}

暂无
暂无

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

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