我正在学习如何通过购物 list 练习来管理应用程序状态。根据说明,我在一个对象中有一个数组,我在其中存储我添加的任何项目:
var state = {
items: []
};
修改state
我使用这个功能:
var addItem = function(state, item) {
state.items.push(item);
};
稍后通过事件监听器调用(并通过 renderList
添加到 DOM,此处未显示):
$('#js-shopping-list-form').submit(function(event){
event.preventDefault();
addItem(state, $('#shopping-list-entry').val());
renderList(state, $('.shopping-list'));
});
如何从我的 state
中的数组中删除特定项目?目的?本质上我想在用户点击 <button class="shopping-item-delete">
时颠倒上面的顺序.
这是最终解决方案的演示:https://thinkful-ed.github.io/shopping-list-solution/
HTML
<body>
<div class="container">
<form id="js-shopping-list-form">
<label for="shopping-list-entry">Add an item</label>
<input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
<button type="submit">Add item</button>
</form>
<ul class="shopping-list">
<li>
<span class="shopping-item">apples</span>
<div class="shopping-item-controls">
<button class="shopping-item-toggle">
<span class="button-label">check</span>
</button>
<button class="shopping-item-delete">
<span class="button-label">delete</span>
</button>
</div>
</li>
</ul>
</div>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script type="text/javascript" src="app.js"></script>
</body>
最佳答案
您可以创建一个函数,如下所示:
var deleteItem = function(state, item) {
var index = state.items.indexOf(item);
if (index > -1) {
state.items.splice(index, 1);
}
};
请注意,Internet Explorer 7 和 8 不支持方法 indexOf
。
关于javascript - 如何从对象内部的数组中删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133095/