Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
https://www.w3schools.com/jsref/jsref_obj_array.asp
array.slice(start, end)
The slice() method slices out a piece of an array into a new array. This example slices out a part of an array starting from array element 1 ("Orange").
start
An integer that specifies where to start the selection (The first element has an index of 0).
Use negative numbers to select from the end of an array. If omitted, it acts like "0"
end (optional)
An integer that specifies where to end the selection - not zero-based index.
If omitted, all elements from the start position and
to the end of the array will be selected. Use negative numbers to select from the end of an array.
let fruits = ["Pear", "Banana", "Apple", "Orange", "Lemon", "Mango", "Lime"];
let citrus = fruits.slice(3);
let partial = fruits.slice(1, 5)
document.getElementById("demo").innerHTML = citrus.join(", ");
document.getElementById("demo2").innerHTML = partial.join(", ");
Here's an excellent example of taking an array, replacing only certain values, and then returning the modified array using slice()
.
handleClick(i)
{
// takes old array, finds the one passed in, and marks it as X.
const squares = this.state.squares.slice();
squares[i] = "X";
console.log(squares[i]);
this.setState({squares: squares});
}