首页 > 解决方案 > 通过在 Javascript 中旋转字符串来打印所有可能性

问题描述

如何在 javascript 中旋转字符串并在不使用任何 javascript 函数的情况下打印字符串的旋转版本,仅for循环。

给定一个字符串:

"hell"

输出:

"lhel", "llhe", "ellh", "hell"

我试过但没有成功

    var str1 = "hell";

    
    let i = 0;
    let len = str1.length - 1;
    let temp;
    
    for (let j = 0; j < len+1; j++) {
        temp = str1[len]
        while (i < len) {
            console.log(str1[i]);
            temp += str1[i];
            i++;
        }
        console.log(temp);
        //console.log(typeof temp, typeof str1)
        str1 = temp;
    }

标签: javascriptstring

解决方案


你快到了!缺少一件事,i应该在循环的每次迭代中重置for,否则,while (i < len)只会“播放”一次:

var str1 = "hell";

let len = str1.length - 1;
let temp;
    
for (let j = 0; j < len+1; j++) {
    let i = 0;  // <-------------------- notice this
    temp = str1[len]
    while (i < len) {
        //console.log(str1[i]);
        temp += str1[i];
        i++;
    }
    console.log(temp);
    //console.log(typeof temp, typeof str1)
    str1 = temp;
}


推荐阅读