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
3 Answers
Reset to default 6You 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条)