Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript deletion of specified elements and specified subscript elements and deduplication code examples

Detailed explanation of JavaScript deletion of specified elements and specified subscript elements and deduplication code examples

伊谢尔伦
伊谢尔伦Original
2017-07-25 15:51:532066browse

Delete the specified elements in the array


/**
 * 参考实例
foreach = function (obj, insp){
  if(obj== null && obj.constructor != Array){
  return [];
}
//obj是要处理的数组,obj==null 表示对象尚未存在;obj.constructor != Array 表示对象obj的属性的构造函数不是数组;
//constructor属性始终指向创建当前对象的构造函数。两个条件均满足,则返回空数组[];
//下面对constructor属性作进一步了解。
var obj= [1, 2, 3, 4]; // 等价于 var obj= new Array(1, 2, 3, 4);
console.log(obj.constructor === Array); // 返回true 表明obj的构造函数为Array;
var foo= function() { }; // 等价于 var foo = new Function();
console.log(foo.constructor === Function); // 返回true 表明foo的构造函数为Function;
var obj = new Foo(); //由构造函数实例化一个obj对象
console.log(obj.constructor === Foo); // 返回true 表明obj的构造函数为Foo;
 */
//删除数组中指定的元素
function del(val, arr)
{
  //检测参数
  if (arr == null && arr.constructor != Array) {
    return [];
  }
  var newarr = []; //不存在的保存到新数组中
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] != val)
      newarr.push(arr[i]);
  }
  return newarr;
}
alert(del(2, [1, 2, 3, 4, 5, 2]));

Remove duplicate elements


/**
 *去除数组中重复的元素
把元素的值存为一个新数组的key,key是不可以重复的,然后变量次数组即可
 */
function unique(data) {
  data = data || [];
  var a = {};
  len = data.length;
  for (var i = 0; i < len; i++) {
    var v = data[i];
    if (typeof(a[v]) == &#39;undefined&#39;) {
      a[v] = 1;
    }
  };
  data.length = 0;
  for (var i in a) {
    data[data.length] = i;
  }
  return data;
}
alert(unique([12,12,12,34]));

Delete the element at the specified subscript of the array


/**
 *删除数组的指定下标元素 
 *
 * i 的值是一直在变的,n的值是只有if条件成立的时候才会变(会依次递增)
 */
Array.prototype.remove=function(dx)
 {
  if(isNaN(dx)||dx>this.length){return false;}
  for(var i=0,n=0;i<this.length;i++)
  {
    if(this[i]!=this[dx])
    {
      this[n++]=this[i]
    }
  }
  this.length-=1
 }
var arr = [1,2,3,4,2,5];
alert(arr);
arr.remove(2);
alert(arr);

The above is the detailed content of Detailed explanation of JavaScript deletion of specified elements and specified subscript elements and deduplication code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn