【问题标题】:How to remove specific object from array on click with javascript如何使用javascript单击从数组中删除特定对象
【发布时间】:2021-11-01 19:00:41
【问题描述】:

这是我的第一个问题: 我建立项目“待办事项”,每次添加任务时,我都会推送到数组对象。 我想知道如何从数组“点击”中删除特定对象。

*这不是原始项目,只是为了了解的示例

 
const input = document.querySelector(".input");
    const maindiv = document.querySelector(".maindiv");
    
    const list = []
    
    input.addEventListener("keydown", function (e) {
        if (input.value && e.keyCode == 13) {
            const div = document.createElement("div")
            const title = document.createElement("h1")
            const btn = document.createElement("button")
    
            title.textContent = input.value
            btn.textContent = "remove"
    
            list.push({ text: input.value })
            btn.addEventListener("click", function (e) {
                for(let i = 0; i < list.length;i++){
                    if(list[i].num == i){
                        list.splice(i,1)
    
                    }
                }
                e.target.parentElement.remove()
            })
            div.appendChild(title)
            div.appendChild(btn)
            maindiv.appendChild(div)
            document.body.appendChild(maindiv)    
        }
    })
<html>
 <body>
    <input type="text" name="" class="input">
    <div class="maindiv"></div> 
    <script src="json.js"></script>   
  </body>
</html>

然后,当我的 div(array.object) 很少时,我想在点击时从数组中删除对象。

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

您可以使用Array.splice 从数组中删除索引处。

您可以使用Array.findIndex获取索引

下面的示例是基本的,但应该为您指明正确的方向。我们从一个包含 10 个值的数组开始,使用findIndex 来获取数组值i-5 的索引。然后,我们使用splice 将其删除。

使用您的代码,您可以搜索要推送到数组的对象的 text 属性,或者您可以添加一些其他标识符以便于搜索。

const arr = []

for (let i = 0; i < 10; i++) {
  arr.push(`i-${i}`)
}

console.log(arr)

const index = arr.findIndex((a) => a === 'i-5')

if (index > -1) { // we found it
  arr.splice(index, 1)
}

console.log(arr)

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2019-06-12
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多