对于循环初始值更改与最终修改的值 JavaScript

for loop initial value change with finally modified value javascript

本文关键字:修改 JavaScript 循环 于循环      更新时间:2023-09-26

在这里,我在for循环中设置了一些初始值,但是在每次执行中,该初始值都会更改。 所以我需要将更改的值放入forloop初始值中

    str = "aabaacaba"
    newStr= str[0];
//for first time newStr length is one. but once "newStr.indexOf(str[i]) == -1" condition satisfied newStr length changed to two. so now newStr length is 2. in for loop the value is to be like "for (var i=2)"
    for (var i=newStr.length;i<str.length; i++) {
        if (newStr.indexOf(str[i]) == -1) {
            newStr = newStr + str[i];//console.log(newStr)
        }
    }

因此,在每次迭代中newStr长度都会有所不同。
我需要javascript或jquery的解决方案。

试试这个:

如果您希望它们在数组中:

str = "aabaacaba"
var newStr = [];
for (var i = 0; i < str.length; i++){
  if (newStr.indexOf(str.charAt(i)) == -1) {
    newStr = newStr.push(str.substring(i,i+1));
    console.log(newStr.length);
  }
}

如果您希望它们在字符串中:

str = "aabaacaba"
var newStr = "";
for (var i = 0; i < str.length; i++){
  if (newStr.indexOf(str.charAt(i)) == -1) {
    newStr = newStr + str.substring(i,i+1);
    console.log(newStr.length);
  }
}

为此使用 while 循环:

var str = "aabaacaba"
var newStr= str[0];
var i = newStr.length;
while (i < str.length) {
    if (newStr.indexOf(str[i]) == -1) {
        newStr = newStr + str[i];
        i = newStr.length;
        //console.log(newStr);
        continue;
    }
    i++;
}