javascript - return an index range of elements in an array - Stack Overflow

How can I return a range of elements in array like so, without using a For Loop, ForEach Statement, etc

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
Add a ment  | 

3 Answers 3

Reset to default 3

You 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

相关推荐

  • javascript - return an index range of elements in an array - Stack Overflow

    How can I return a range of elements in array like so, without using a For Loop, ForEach Statement, etc

    8小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信