2016-09-27 92 views
-2

我有一个数组的多个项目,选择在阵列

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

我不知道数组是多久,我想3之后要选择一切我该怎么做呢?

+0

你可以像'arr.slice(arr.indexOf(3)+1)' – Redu

+0

@Redu我甚至扩展这个为'arr.slice(arr.indexOf( 3)+1 || arr.length)'如果'arr'不包含3,则返回一个空的Array。虽然没有明确要求。 – Thomas

+0

我必须投票,“不显示任何研究工作”。 – TylerY86

回答

-1

在你例如,“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());

1

使用.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); 
-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]

+0

请务必澄清,这会修改原始集合。 – TylerY86

+0

发表了评论,谢谢 – Marcin

+0

@MarcinC。在我的情况下,用户输入数组。所以如果我不知道什么时候是3,我该怎么办? – eclipseIzHere