在循环中如何访问当前的数量? [英] How can the current number of i be accessed in a for of loop?

查看:83
本文介绍了在循环中如何访问当前的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个for循环,分配给这个例子的变量( i )的值等于 array [i] 如果它是一个正常的循环,将相等。



我想要的是如何 i 的数组索引

  let array = [one,two,three]; 

(让我的数组){
console.log(i); //通常记录循环一:一,循环二:二,循环三:三。
console.log(/ *什么等于当前索引* /); //我想要记录的周期1:循环2:2,循环3:3.
}


解决方案

没有什么简单的...如果你想简单访问 item和索引在一个数组中的循环中,使用 forEach eg

  array.forEach(function(item,index){
...
});

或作为T.J. Crowd指针(我错过了ES6标签)

  array.forEach((item,index)=> {
...
});

像许多编程语言一样,javascript有多种方式来做类似的事情,技巧在于选择正确的工作工具


Given a for of loop the value of the assigned the variable(i for this example) is equal to what array[i] would equal if it was a normal for loop. How can the index of the array the that i is currently on be accessed.

What I want

let array = ["one", "two", "three"];

for (let i of array) {
  console.log(i);// normally logs cycle one : "one", cycle two : "two", cycle three : "three".
  console.log(/*what equals the current index*/);// what I want to log cycle one : 1, cycle two : 2, cycle three : 3. 
}

解决方案

nothing simple ... if you want "simple access" to both the item and the index in a loop over an array, use forEach e.g.

array.forEach(function(item, index) { 
... 
});

or as T.J. Crowder pointer out (and I missed the ES6 tag)

array.forEach((item, index) => { 
    ... 
});

like many programming languages, javascript has multiple ways to do similar things, the skill is in choosing the right tool for the job

这篇关于在循环中如何访问当前的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆