This is a short cut of my addItem function in my todo app, i don't really understand what slice does in this value: this.state.newItem.slice(). Can anybody explain me? Thank you so much!
constructor(props) {
super(props);
this.state = {
newItem: "",
list: []
};
addItem() {
// create a new item with unique id
const newItem = {
id: 1 Math.random(),
**value: this.state.newItem.slice()**
};
// copy current list of items
const list = [...this.state.list];
// add the new item to the list
list.push(newItem);
// update state with new list, reset the new item input
this.setState({
list,
newItem: ""
});
}
CodePudding user response:
Since the slice
returns new string, the slice
might have used to copy the string in the above code. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
CodePudding user response:
First of all why are you use slice method? If you used it to trim your value. you use The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string. Syntax. string.trim().