javascript - 从数组中删除特定元素

标签 javascript arrays reactjs filter

state = { filters: ['all'] }


this.state.filters.includes('humans') ? 
    this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown)

我使用的条件是,当我点击一个按钮时,项目('humans')被推到状态,当我再次点击同一个按钮时,我需要从中删除项目('humans')阵列。推送工作正常,我需要帮助删除它。我像上面的代码一样使用过滤器,它不会再次添加到数组中但也不会删除。 提前致谢。

最佳答案

使用:

let index = this.state.filters.indexOf('humans');
if (index !== -1)
   this.state.filters.splice(index, 1);

或者你最好按照这种方法来 avoid mutating the state在 react 中:

let array = [...this.state.filters]; // make a separate copy of the array
let index = array.indexOf('humans')
if (index === -1) { // not in the array
   array.push('humans');
   this.setState({filters: array});
} else { // exists in the array
   array.splice(index, 1);
   this.setState({filters: array});
}

关于javascript - 从数组中删除特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54092167/

相关文章:

javascript - Jquery Submit() 不传递文件数据

javascript - 如何为 cypress-audit 包生成的灯塔报告指定自定义名称

javascript - 通过键删除嵌套结构中的对象

php - 将 mysql 值分配到多维数组中

javascript - 从 React TypeScript 组件调用外部 Javascript 函数

javascript - 通过Javascript访问CSS计算变量

javascript - 在 Javascript 中使用一维数组访问多维数组

javascript - 使用 inArray() 检查 javascript 数组中的数字

javascript - react : Dynamically created state variable

javascript - Reactjs 获取身份验证和访问 token ,无法解析响应