最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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'));

发布评论

评论列表(0)

  1. 暂无评论