I am learning how to manage application state via a shopping list exercise. Per the instructions, I have an array inside an object where I store any items I add:
var state = {
items: []
};
To modify state
I use this function:
var addItem = function(state, item) {
state.items.push(item);
};
which is called later via an event listener (and added to the DOM via renderList
, not shown here):
$('#js-shopping-list-form').submit(function(event){
event.preventDefault();
addItem(state, $('#shopping-list-entry').val());
renderList(state, $('.shopping-list'));
});
How can I remove a specific item from the array inside my state
object? Essentially I want to reverse the sequence above when the user clicks on <button class="shopping-item-delete">
.
Here's a demo of the final solution: https://thinkful-ed.github.io/shopping-list-solution/
<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>
You could create a function as follows:
var deleteItem = function(state, item) {
var index = state.items.indexOf(item);
if (index > -1) {
state.items.splice(index, 1);
}
};
Note that the method indexOf
is not supported in Internet Explorer 7 and 8.
If you know the index of the item you can use. You can determine the index by value of item
state.items.splice(indexOfItemToRemove, 1);
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
There are a couple of ways to remove elements from Arrays:
shift
will remove the first item from the beginning
pop
will remove the last item from the end.
splice
allows you to remove an element at a desired location
Note that all of these will modify the original array (they work "in-place") as opposed to returning a new array.
You may loop over the items
var removeItem = function(state, item) {
for(var i = state.items.length - 1; i >= 0; i--) {
if(state.items[i] === item) {
state.items.splice(i, 1);
break;
}
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.