只需要重置 Javascript 数组的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11413887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:07:15  来源:igfitidea点击:

Need to reset just the indexes of a Javascript array

javascriptarraysindexingindexof

提问by Adnan Baliwala

I have a forloop which returns an array.

我有一个for循环,它返回一个数组。

Return:

返回:

1st loop:
arr[0]
arr[1]
arr[2]
arr[3]

Here the length I get is 4(Not a problem).

我得到的长度是4(不是问题)。

Return:

返回:

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

Here the length I get is 9.

我得到的长度是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 every time it starts from 0so that I get proper length in all the loops?

我在这里想要的是索引的实际计数,即我需要它5。我怎样才能做到这一点。有没有一种方法可以让我每次开始时进入每个循环,0以便在所有循环中获得适当的长度?

回答by Dag Sondre Hansen

This is easily done natively using Array.filter:

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

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

回答by danmcardle

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

回答by hallodom

Perhaps "underscore.js" will be useful here.

也许“underscore.js”在这里会有用。

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

_.compact()函数返回没有 的数组副本undefined

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

请参阅:http: //underscorejs.org/#compact

回答by M_R_K

Easy,

简单,

var filterd_array = my_array.filter(Boolean);