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

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《js移除元素属性(jquery删除所有子元素)》的相关信息,《js移除元素属性(jquery删除所有子元素)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《js移除元素属性(jquery删除所有子元素)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

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;}// Usageconsole.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 = 3var arr = [1, 2, 3, 4, 5, 3]arr = arr.filter(function(item) { return item !== value})console.log(arr)// [ 1, 2, 4, 5 ]
笨笨网美国主机,w ww.2 b p .n e t
提醒:《js移除元素属性(jquery删除所有子元素)》最后刷新时间 2025-03-21 11:17:20,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《js移除元素属性(jquery删除所有子元素)》该内容的真实性请自行鉴别。