Javascript: How to pass an array with specific index to a function? - Stack Overflow

Let say I have an array:-var arr = [0,1,2,3,4]I need to pass only "1" and "4" to fu

Let say I have an array:-

var arr = [0,1,2,3,4]

I need to pass only "1" and "4" to function below

function func1(onlyArray){
     //Do Stuff...
}

I have tried both but both also dont work

func1(arr[1,4])
func1(arr[[1],[4]])

Can anyone show me the right way or give me some keyword?

Let say I have an array:-

var arr = [0,1,2,3,4]

I need to pass only "1" and "4" to function below

function func1(onlyArray){
     //Do Stuff...
}

I have tried both but both also dont work

func1(arr[1,4])
func1(arr[[1],[4]])

Can anyone show me the right way or give me some keyword?

Share Improve this question asked Oct 10, 2017 at 19:37 vbnewbievbnewbie 2267 silver badges27 bronze badges 6
  • 2 func(arr[1], arr[4]) – Egor Stambakio Commented Oct 10, 2017 at 19:38
  • @wostex but the function only accept one parameter, will this detect as two parameter? – vbnewbie Commented Oct 10, 2017 at 19:40
  • @vbnewbie, use this: func([arr[1], arr[4]]) – Mihai Alexandru-Ionut Commented Oct 10, 2017 at 19:41
  • What is the type of the parameter? – davidbuzatto Commented Oct 10, 2017 at 19:41
  • Do you have control over the function or are you locked into it only accepting a single argument? If you can't change the function, how will the function know how many parameters it's receiving? – j08691 Commented Oct 10, 2017 at 19:43
 |  Show 1 more ment

3 Answers 3

Reset to default 6

You can use this: func([arr[1], arr[4]])

We are taking the elements at index 1 and 4 of the array arr and creating a new array with those elements. Then we pass that newly created array to func.

If you need a single array instead of 2, use this:

var arr = [0,1,2,3,4];

function func1(onlyArray){
     //Do Stuff...
    console.log(onlyArray); // [1, 4]
}

func1(arr.filter((item,index) => index === 1 || index === 4));

So using your array:

var arr = [0,1,2,3,4];

and your function:

function myFunction(newArr){ //Do stuff console.log(newArr); };

You can wrap the array indexes you want to use inside of their own array when you call the function, like the following:

myFunction([arr[1], arr[4]]); //Output is [1, 4]

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744144103a4560341.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信