How can I "reset" an array's keys?
This question already has an answer here:
For example, you can use Array.prototype.filter
method.
var array = [];
array[30] = 1;
array.length; // 31
var compactArray = array.filter(function (item) {
return item !== undefined;
});
compactArray.length; // 1
If it's an object, for..in
loop will be usefull
var array = { 31: 1};
var compactArray = [];
for (var i in array) {
compactArray.push(array[i]);
}
You can loop throw array and if its a valid item, then push in another array.
Also, when you do something like this,
var arr = [];
arr[3] = 15;
arr
is actually [null, null, null, 15]
Following is an example.
(function() {
var arr = [];
var result = [];
arr[3] = 15;
arr[7] = 20;
arr[19] = -1;
console.log(arr);
console.log(JSON.stringify(arr))
arr.forEach(function(item) {
if (item) {
result.push(item);
}
})
console.log(result);
console.log(JSON.stringify(result));
})()
如果你的意思是你的对象是这样的
var obj = {3: 15, 7: 20, 19: -1};
var output = {};
var counter = 0;
for ( var id in obj )
{
output[ String( counter ) ] = obj[ id ];
counter++;
}
console.log( output );
链接地址: http://www.djcxy.com/p/37740.html
上一篇: 从数组逻辑中删除空字符串
下一篇: 我怎样才能“重置”一个数组的键?