value-at
This is a simple JavaScript getter/setter function for retrieving or changing a value in an array.
Installation
npm install value-at --save
Usage
Quick guide to the syntax:
valueAt(array, index[, replacementValue][, isCloned])
Using as a get function
Positive
var valueAt = ; var array = 1 2 3 4 5; var value = ; // value = 2
That isn't all that special since you can do the same thing with native JavaScript by just using array[1]
.
The advantage this has is that it also works for negative index values.
Negative
var valueAt = ; var array = 1 2 3 4 5; var value = ; // value = 4
Using as a set function
Positive
var valueAt = ; var array = 1 2 3 4 5; var newArray = ; // array = [1, 2, 3, 4, 5];// newArray = [1, "a", 3, 4, 5];
Note that valueAt
doesn't change the original array by default. It returns with an altered shallow clone of the original array.
Negative
var valueAt = ; var array = 1 2 3 4 5; var newArray = ; // array = [1, 2, 3, 4, 5];// newArray = [1, 2, 3, "b", 5];
Altering the original array
If you do want to alter the original array, set the 4th parameter to false
.
var valueAt = ; var array = 1 2 3 4 5; ; // array = [1, 2, 3, "b", 5];