简体   繁体   中英

Choosing multiple items in array

I have an array,

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

I don't know how long the array is, and I want to select everything after 3. How do i do that?

Use .indexOf to find the index of 3, and then use .slice to find everything after that element:

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

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

You splice function:

 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]

In your example, the "3" is located in the slot for index two. If you want everything after the third element (index two) the first function will do that.

If you want everything after the first 3 found, then the second function will do that.

 // 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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