How can I return a range of elements in array like so, without using a For Loop, ForEach Statement, etc.
var array = ["1", "2", "3"]
console.log(array[0-3]);
//result
//1
//2
//3
How can I return a range of elements in array like so, without using a For Loop, ForEach Statement, etc.
var array = ["1", "2", "3"]
console.log(array[0-3]);
//result
//1
//2
//3
Share
Improve this question
asked Oct 13, 2019 at 5:46
user11077261user11077261
3 Answers
Reset to default 3You can use slice
var array = ["1", "2", "3"]
let indexRange = (arr, start, end) => {
return arr.slice(start, end)
}
console.log(indexRange(array, 0, 3));
If your range is string then you can use split and slice
var array = ["1", "2", "3"]
let indexRange = (arr, range) => {
let [start,end] = range.split('-').map(Number)
return arr.slice(start, end)
}
console.log(indexRange(array, "0-3"));
use slice() method. slice() method returns the selected elements in an array, as a new array object.
SYNTAX:
array.slice(start, end)
var array = ["1", "2", "3"]
console.log(array.slice(0,3));
//result
//1
//2
//3
You can create a function & then pass the range as a string. Inside the function body split the range by the delimiter -
. Then join the elements of the array and create a string. Use substr
to get the element between the range. This will create a new string & while returning again split it to create an array
var array = ["1", "2", "3", "4", "5"]
function getElemInRange(range) {
let getRange = range.split('-');
return array.join('')
.substr(parseInt(getRange[0], 10), parseInt(getRange[1], 10))
.split('');
}
console.log(getElemInRange('0-3'));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745556069a4632827.html
评论列表(0条)