如何从数组中获取子数组?

2020/10/07 23:01 · javascript ·  · 0评论

我有var ar = [1, 2, 3, 4, 5]并想要一些函数getSubarray(array, fromIndex, toIndex),调用的结果getSubarray(ar, 1, 3)是新数组[2, 3, 4]

看一眼 Array.slice(begin, end)

const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);

为了简单地使用slice,请使用我对Array Class的扩展:

Array.prototype.subarray = function(start, end) {
    if (!end) { end = -1; } 
    return this.slice(start, this.length + 1 - (end * -1));
};

然后:

var bigArr = ["a", "b", "c", "fd", "ze"];

测试1

bigArr.subarray(1, -1);

<[“ b”,“ c”,“ fd”,“ ze”]

测试2:

bigArr.subarray(2, -2);

<[“ c”,“ fd”]

测试3:

bigArr.subarray(2);

<[“ c”,“ fd”,“ ze”]

对于使用其他语言(例如Groovy)的开发人员来说,可能会更容易。

const array_one = [11, 22, 33, 44, 55];
const start = 1;
const end = array_one.length - 1;
const array_2 = array_one.slice(start, end);
console.log(array_2);

问题是实实在在的一个新的数组,所以我认为一个更好的解决办法是结合Abdennour•图米的答案与克隆功能:

function clone(obj) {
  if (null == obj || "object" != typeof obj) return obj;
  const copy = obj.constructor();
  for (const attr in obj) {
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  }
  return copy;
}

// With the `clone()` function, you can now do the following:

Array.prototype.subarray = function(start, end) {
  if (!end) {
    end = this.length;
  } 
  const newArray = clone(this);
  return newArray.slice(start, end);
};

// Without a copy you will lose your original array.

// **Example:**

const array = [1, 2, 3, 4, 5];
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]

console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]

[ http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]

本文地址:http://javascript.askforanswer.com/ruhecongshuzuzhonghuoquzishuzu.html
文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!