js移除元素属性(jquery删除所有子元素)

Array.prototype.indexOf()

用indexOf找到你想删除的数组元素的索引,然后用splice删除该索引。

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

splice的第二个参数是要移除的元素的数量。注意,splice修改了原地的数组,并返回一个包含被移除的元素的新数组。

为了完整起见,这里有一些函数。第一个函数只删除单一的出现(即从[2,5,9,1,5,8,5]中删除5的第一个匹配),而第二个函数则删除所有出现的情况。

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

在TypeScript中,这些函数可以添加类型参数。

function removeItem<T>(arr: Array<T>, value: T): Array<T> { 
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

Array.prototype.filter()

var value = 3

var arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(function(item) {
    return item !== value
})

console.log(arr)
// [ 1, 2, 4, 5 ]
(0)
仰望辉煌。  的头像仰望辉煌。  

相关推荐

发表回复

登录后才能评论