javascript删除数组元素
/**
* js 中的数组删除, 实现思想
* 将数组中的引用下标指向该数组的下一个元素核心代码
* array[i] = array[i + 1];
* array.length - 1;
*
运用javascript中的原型prototype给js的Array 类添加删除元素方法
*/
根据所填入的下标进行删除数组中的元素
Array.prototype.removeAttrByIndex = function(index)
{
for(var i = index; i < this.length; i ++)
{
this[i] = this[i + 1];
}
this.length = this.length - 1;
}
若填入的是该数组的中的元素非元素下标(条件: 该数组中的元素不重复)
算法思路:
1. 循环遍历js数组,找到与填入的元素的下标
2.根据下标继续进行删除元素的算法
array[i] = array[i + 1];
array.length - 1;
Array.prototype.removeAttrByText = function(text)
{
//声明一个变量用于定位下标</span>
var flag = -1;
for(var i = 0; i < this.length; i ++)
{
if(this[i] == text)
{
flag = i;
break;
}
}
if(flag != -1)
{
for(var j = flag ; j < this.length; j ++)
{
this[j] = this[j + 1];
}
this.length = this.length - 1;
}else
{
alert('未找到元素');
}
}
定义一个全新的方法, 使得程序自己判断用户所填的是数字还是元素
运用 isNaN()方法判断所填写是否为数字
Array.prototype.remove = function(obj)
{
var temp = -1;
if(isNaN(obj))//非数字 找寻下标
{
for(var i = 0;i < this.length; i++)
{
if(this[i] == obj)
{
temp = i;
break;
}
}
}
else
{
temp = obj;
}
if(temp != -1)
{
for(var j = temp; j < this.length; j ++)
{
this[j] = this[j +1 ];
}
this.length = this.length - 1;
}else
{
alert('未有该元素');
}
}
附: 使用demo html
<script>
window.onload = function()
{
var array = new Array();
array.push('a');
array.push('b');
array.push('c');
array.push('d');
array.push('e');
array.remove(1);
array.remove('d');
for(var i = 0; i < array.length ; i ++)
{
alert(array[i]);
}
}
Array.prototype.remove = function(obj)
{
var temp = -1;
if(isNaN(obj))//非数字 找寻下标
{
for(var i = 0;i < this.length; i++)
{
if(this[i] == obj)
{
temp = i;
break;
}
}
}
else
{
temp = obj;
}
if(temp != -1)
{
for(var j = temp; j < this.length; j ++)
{
this[j] = this[j +1 ];
}
this.length = this.length - 1;
}else
{
alert('未有该元素');
}
}
</script>
ps : 欢迎加我微信,一起探讨技术,注明csdn上看见的即可