几个常用的Javascript函数

博客主要针对IE在5.5版本之前不支持数组的push和pop函数的问题,给出了替代方案。定义了判断数组元素是否有效的函数,以及获取数组大小、模拟push和pop操作的函数。还展示了网上老外写的通过原型链添加push和pop方法的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


// *******************************************************
// replacements for unsupported array functions (because arrayname.push(var)
// and arrayname.pop() are not implemented in IE until version 5.5)
function thearrayisgood(thearray,i) {
if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
return false;
else
return true;
}

function getarraysize(thearray) {
// replacement for arrayname.length property
for (i = 0; i < thearray.length; i++) {
if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
return i;
}
return thearray.length;
}

function arraypush(thearray,value) {
// replacement for arrayname.push(value)
thearraysize = getarraysize(thearray);
thearray[thearraysize] = value;
return thearray[thearraysize];
}

function arraypop(thearray) {
// replacement for arrayname.pop()
thearraysize = getarraysize(thearray);
retval = thearray[thearraysize - 1];
delete thearray[thearraysize - 1];

thearray.length--; <<==我加了这句,很关键,否则出错
return retval;
}

// *******************************************************

另外给出网上几个老外写的

function Array_pop() {
var response = this[this.length - 1]
this.length--
return response
}

if (typeof(Array.prototype.pop) == "undefined") {
Array.prototype.pop = Array_pop
}

function Array_push() {
var A_p = 0
for (A_p = 0; A_p < arguments.length; A_p++) {
this[this.length] = arguments[A_p]
}
return this.length
}

if (typeof Array.prototype.push == "undefined") {
Array.prototype.push = Array_push
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值