繁体   English   中英

选择数组中的多个项目

[英]Choosing multiple items in array

我有一个数组,

var arr=[1,2,3,4,5,6,7,8,9,10];

我不知道数组有多长,我想选择 3 之后的所有内容。我该怎么做?

使用.indexOf查找 3 的索引,然后使用.slice查找该元素之后的所有内容:

// find the index of the element 3
var indexOfThree = arr.indexOf(3);

// find everything after that index
var afterThree = arr.slice(indexOfThree + 1);

你拼接功能:

 var a = [1,2,3,4,5,6,7,8,9,10]; var b = a.splice( 3, a.length ); alert (b); // [4, 5, 6, 7, 8, 9, 10] alert (a); // [1, 2, 3]

在您的示例中,“3”位于索引二的插槽中。 如果您想要第三个元素(索引二)之后的所有内容,第一个函数将执行此操作。

如果您想要找到前 3 个之后的所有内容,则第二个函数将执行此操作。

 // This finds all content after index 2 Array.prototype.getEverythingAfterIndexTwo = function() { if (this.length < 4) { return []; } else { return this.slice(3); } } // This finds the first 3 in the array and returns any content in later indices Array.prototype.getEverythingAfterAThree = function() { // returns array if empty if (!this.length) return this; // get the index of the first 3 in the array var threeIndex = this.indexOf(3); // if no 3 is found or 3 is the last element, returns empty array // otherwise it returns a new array with the desired content if (!~threeIndex || threeIndex === this.length-1) { return []; } else { return this.slice(threeIndex + 1); } } var arr=[1,2,3,4,5,6,7,8,9,10]; console.log(arr.getEverythingAfterIndexTwo()); console.log(arr.getEverythingAfterAThree());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM