簡體   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