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

时间:2014-03-12 06:54:57

标签: javascript html

我有一个很长的字符串。

var string = "This is a long string."

我还有一个将字符串下载到"路径"。

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

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

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

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

2 个答案:

答案 0 :(得分:1)

以下是一个评论如何执行此操作的示例:

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;}
}

答案 1 :(得分:0)

计算字符串长度 你想要的除以2向上或向下

然后在切换后执行一个for循环。

Somethig喜欢这个

//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
}