javascript数组的删除
2016-05-23 20:45
387 查看
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上看见的即可
相关文章推荐
- 深入解析js中基本数据类型与引用类型,栈和队的区别
- Why fastjson so fast?
- js下载文件功能
- 使用Canvas绘制不完美/不规则的圆形
- 没有错误和没有明显错误的差别
- JSON和XML的解析[XStream]
- JSON的解析[Jackson]
- js制作淘宝放大镜效果
- js中通过javascriptbBridge调用客户端方法
- JSP自定义标记
- JavaScript闭包中的this
- Js中的空值判断
- 关于JS面向对象的问题一
- [Effective JavaScript 笔记]第15条:当心局部块函数声明笨拙的作用域
- javascript 判断一个数字是否为质数实现方式若干 by FungLeo
- 推荐三款强大的Js图表库
- 无阻塞加载javascript脚本
- JavaScript正则表达式大全(过滤Emoji的最佳实践)
- [置顶] ExtJs常用布局--layout详解(含实例)
- 钉钉开发系列(四)获取JS票据