添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

js for in循环获取下标

在 JavaScript 中,使用 for...in 循环可以遍历对象的属性。如果要获取数组的下标,则可以使用 for...in 循环,并在循环体内部使用数组的 hasOwnProperty() 方法来判断当前属性是否是数组的自有属性。

var arr = [1, 2, 3, 4, 5];
for (var index in arr) {
    if (arr.hasOwnProperty(index)) {
        console.log(index);

但是最好的方式是使用 for of 循环,这样可以避免判断hasOwnProperty.

for (let i of arr.keys()) {
  console.log(i);

或者使用forEach

arr.forEach(function(value, index) {
  console.log(index);

也可以使用 map 方法

arr.map(function(value, index) {
  console.log(index);

这些都是可以获取数组下标的方式。

  •