需要仅重置Javascript数组的索引

时间:2021-06-03 04:19:28

I have a for loop which returns an array : return

我有一个返回数组的for循环:return

1st loop:
arr[0]
arr[1]
arr[2]
arr[3] Here length that i get is 4 (Not a problem)

return

2nd loop
arr[4]
arr[5]
arr[6]
arr[7] 
arr[8] 

Here length that i get is 9. return

我得到的长度是9.返回

What i want here is the actual count of the indexes i.e i need it to be 5. How can i do this..And is there a way that when i enter each loop everytime it starts from 0 so that i get proper length in all the loops?

我想要的是索引的实际数量,即我需要它是5.我怎么能这样做...当我每次从0开始进入每个循环时,有一种方法可以让我得到适当的长度循环?

3 个解决方案

#1


27  

This is easily done natively using Array.filter:

这很容易使用Array.filter本地完成:

resetArr = orgArr.filter(function(){return true;});

#2


4  

You could just copy all the elements from the array into a new array whose indices start at zero.

您可以将数组中的所有元素复制到索引从零开始的新数组中。

E.g.

function startFromZero(arr) {
    var newArr = [];
    var count = 0;

    for (var i in arr) {
        newArr[count++] = arr[i];
    }

    return newArr;
}

// messed up array
x = [];
x[3] = 'a';
x[4] = 'b';
x[5] = 'c';

// everything is reordered starting at zero
x = startFromZero(x);

#3


2  

Perhaps underscore.js will be useful here.

也许underscore.js在这里很有用。

The _.compact() function returns a copy of the array with no undefined.

_.compact()函数返回没有未定义的数组副本。

See: http://underscorejs.org/#compact

#1


27  

This is easily done natively using Array.filter:

这很容易使用Array.filter本地完成:

resetArr = orgArr.filter(function(){return true;});

#2


4  

You could just copy all the elements from the array into a new array whose indices start at zero.

您可以将数组中的所有元素复制到索引从零开始的新数组中。

E.g.

function startFromZero(arr) {
    var newArr = [];
    var count = 0;

    for (var i in arr) {
        newArr[count++] = arr[i];
    }

    return newArr;
}

// messed up array
x = [];
x[3] = 'a';
x[4] = 'b';
x[5] = 'c';

// everything is reordered starting at zero
x = startFromZero(x);

#3


2  

Perhaps underscore.js will be useful here.

也许underscore.js在这里很有用。

The _.compact() function returns a copy of the array with no undefined.

_.compact()函数返回没有未定义的数组副本。

See: http://underscorejs.org/#compact