使用Javascript - 重建索引数组
问题描述:
这里是我的榜样。你能告诉我怎样才能使数组已经连续键
Here is my example. Can you tell me how can I make the array have consecutive keys
array[0]
array[1]
array[2]
当我有
var testArray = new Array();
testArray[3]="qwerty";
testArray[7]="asdfgh";
testArray[13]="zxcvbn";
var testString = testArray.join();
编者按:提问者要他重新索引数组的
Editor's note: The asker wants to reindex his array.
答
如果你不介意使用JavaScript 1.6(注:此code使用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;
};
}