FreeCodeCamp:Slasher Flick

要求:

 

打不死的小强!

 

返回一个数组被截断n个元素后还剩余的元素,截断从索引0开始。

 

结果:

 

  • slasher([1, 2, 3], 2) 应该返回 [3].
  • slasher([1, 2, 3], 0) 应该返回 [1, 2, 3].
  • slasher([1, 2, 3], 9) 应该返回 []slasher([1, 2, 3], 4) 应该返回 [].
  • slasher(["burgers", "fries", "shake"], 1) 应该返回 ["fries", "shake"].
  • slasher([1, 2, "chicken", 3, "potatoes", "cheese", 4], 5) 应该返回 ["cheese", 4].

 

 

代码:

方法一:使用slice()

 1 //Array.slice()
 2 
 3 function slasher(arr, howMany) {
 4   // it doesn't always pay to be first
 5   var newarr;
 6   
 7   if(arr.length>howMany){
 8     newarr=arr.slice(howMany);
 9     return newarr;
10   }else{
11     newarr=[];
12     return newarr;
13   }
14   //return arr;
15 }
16 
17 slasher([1, 2, 3], 2);

方法二:使用splice()

1 function slasher(arr, howMany) {
2   // it doesn't always pay to be first
3   arr.splice(0,howMany);
4 
5   return arr;
6 }

 

posted @ 2016-11-09 21:40  tmj  阅读(206)  评论(0编辑  收藏  举报