for循环初始值更改,最后修改了值javascript

时间:2016-01-30 07:30:10

标签: javascript jquery arrays for-loop

这里我在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中使用解决方案。

2 个答案:

答案 0 :(得分:0)

使用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++;
}

答案 1 :(得分:0)

试试这个:

如果您想要它们在数组中:

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