javascript - 通过在 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;
}
解决方案
你快到了!缺少一件事,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;
}
推荐阅读
- python - 如何在没有 CUDA 的情况下为 PyTorch 构建 CUDA 自定义 C++ 扩展?
- javascript - 部分字符串匹配 - 动态字符串
- xamarin.forms - Xamarin.Forms - 选择键盘语言
- firebase - Flutter Firebase 依赖项和服务
- javascript - 仅从地图(其值为数组)中获取值到数组打字稿
- flutter - Flutter/ReactiveForms:如何在 ReactiveTextField 中处理与 TextFormField 中相同的控制器?
- java - 如何从地图中分配元素,以使元素总和不增加上限
- pointers - 如何对动态移动对象的容器拥有的对象进行有效引用?
- php - Curl 获取网站的描述,但不是从元标记中获取
- python - 尝试使用 pylibftdi 从旧小工具读取数据失败