重新索引数组 [英] Reindexing an array
本文介绍了重新索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是我的例子.
你能告诉我如何让数组有连续的键吗?我想重新索引我的数组.
Can you tell me how can I make the array have consecutive keys? I want to reindex my array.
目前我有:
var testArray = new Array();
testArray[3]="qwerty";
testArray[7]="asdfgh";
testArray[13]="zxcvbn";
console.log(testArray);
但我想获取索引 0、1 和 2(以此类推)处的值:
But I'd like to get the values at indices 0, 1 and 2 (and so on):
["qwerty", "asdfgh", "zxcvbn"]
推荐答案
如果您不介意使用 javascript 1.6 :(注意:此代码使用 jQUEry 库)
If you don't mind using javascript 1.6: (note: this code uses the jQUery library)
var testArray = new Array();
testArray[3]="qwerty";
testArray[7]="asdfgh";
testArray[13]="zxcvbn";
var testString = testArray.filter(function (item) { return item != undefined }).join();
$(function(){
$('#write').text(testString);
});
过滤器原型:
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
这篇关于重新索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文