如何快速在“ for循环”中更改i变量

时间:2020-06-15 09:08:12

标签: java ios swift for-loop

您好,我想迅速执行此Java代码。在Java中,代码为:

public class Test{

 public static void main(String []args){
    int[] arr = new int[6];
    arr[0] = 0;
    arr[1] = 1;
    arr[2] = 2;
    arr[3] = 3;
    arr[4] = 4;
    arr[5] = 5;
    for(int i=0;i<=5;i++){
    System.out.println("i="+i);
    if(arr[i] % 2 == 0) continue;
    arr[i] = arr[i] + 1;
    i--;
    }
 }

}

控制台输出为:

i = 0 i = 1 i = 1 i = 2 i = 3 i = 3 i = 4 i = 5 i = 5

Swift中的相同代码是

var arr = [0,1,2,3,4,5]
for var i in 0...5 {
    print("i=\(i)")
    if (arr[i] % 2 == 0) {continue}
    arr[i] += 1
    i = i-1
}

在Swift代码中,输出为:

i = 0 i = 1 i = 2 i = 3 i = 4 i = 5

问题是,即使编译器强迫我将i设置为var进行编译,i的值也不会在循环中发生变化,并且每次设置的值0 ... 5时,i都会得到。

我的问题是如何在Swift中编写Java代码,以便在需要时可以对i进行修改

1 个答案:

答案 0 :(得分:3)

使用while循环:

:: HTML DOC ::

 <form>
    <label for="name">Name</label>
    <input type="text" name='name' id='name' placehodler='enter name' required>
    <button type="submit" id='sbt-btn'>Store in LS</button>
</form>
-----------------------------------------------------------------------------  

:: JS DOC ::

//DOM fetch 
const form = document.querySelector('form');

form.addEventListener('submit', () => {

   const inputName = form.name.value;      //name is the input field's ID                                    
   localStorage.setItem('name', inputName); //add name to localStorage

});

//retrive name from local storage

if (localStorage.getItem('name')) {
   userName = localStorage.getItem('name');
     form.innerHTML += `<p>Hi ${userName}!</p>`;
 }

/* it will append this html template only when the local storage has a key 
'name' with some value in it. */

请注意第二个更改:继续循环时,您只需要向var i = 0 while i <= 5 { print("i=\(i)") if (arr[i] % 2 == 0) { i += 1 continue } arr[i] += 1 } 加1即可,而不是从i末尾减去1,因为在while循环中,i通常不会改变。