gpt4 book ai didi

javascript - 如果值为真,则使用拼接删除数组项

转载 作者:行者123 更新时间:2023-11-30 09:17:15 25 4
gpt4 key购买 nike

我正在尝试使用 array.splice 方法从数组中删除为 true 的选中项。它似乎大部分时间都有效,但由于某些原因,有时会检查两个或三个项目,并且当我运行拼接数组项目的函数时,只有一个项目从检查列表中删除。

我已经尝试通过数组进行映射并返回删除了拼接项的新数组,这种方法可行,但并非总是如此。我正在用两个参数(索引和项目)映射数组。我正在创建一个 if 语句,如果项目被选中或完成,则通过 (index, 1) 将其删除。之后我将返回新数组。问题发生在 removeCheckedBeer 函数

  // if there is no item string, create an empty array
const items = JSON.parse(localStorage.getItem('items')) || []

function addItem(e) {
// prevent the form from submitting
e.preventDefault()
const text = (this.querySelector('[name=item]')).value
const item = {
text,
done: false
}
items.push(item)
// rerenders list without having to reload the page
populateList(items, itemsList)
localStorage.setItem('items', JSON.stringify(items))
this.reset()
}

// function removes all items in the array
const removeAllItems = e => {
e.preventDefault()
items.splice(0)
localStorage.setItem('items', JSON.stringify(items))
populateList([], itemsList)
}

// remove all checked items
const removeCheckedBeer = e => {
e.preventDefault()
items.map((item, index) => {
if (item.done === true) {
console.log(index, item)
items.splice(index, 1)
}
return items
})
localStorage.setItem('items', JSON.stringify(items))
populateList(items, itemsList)
}

// toggle a single item
const toggleDone = e => {
if (!e.target.matches('input')) return // skip this unless it's an input
const el = e.target
const index = el.dataset.index
// toggle from done to !done
items[index].done = !items[index].done
localStorage.setItem('items', JSON.stringify(items))
}

// toggle inventory of all items to true or false
const toggleAllItems = e => {
items.forEach((item, index, array) => {
e.target.name === 'checkAll' ? (items[index].done = true) : (items[index].done = false)
console.log(e.target.name)
})
localStorage.setItem('items', JSON.stringify(items))
populateList(items, itemsList)
}

const populateList = (beers = [], beerList) => {
// map through the array, and create a new array to render the beer list
beerList.innerHTML = beers.map((beer, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}"
${beer.done ? 'checked' : ''} />
<label for="item${i}">${beer.text}</label>
</li>
`
}).join('')
}

所以我希望从第一个选中项目的索引开始的数组中删除选中项目的数量。结果是该项目被删除,但有时一次只删除一个项目。有时不止一项被删除。有人可以解释我的功能发生了什么吗?

最佳答案

splice() 的问题在于,从数组中删除该元素会将所有其他元素也向下移动一位。最好使用filter():

items = items.filter(e => e.done !== true);

关于javascript - 如果值为真,则使用拼接删除数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54189682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com