admin管理员组文章数量:1396778
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]
本文标签: Javascript How to pass an array with specific index to a functionStack Overflow
版权声明:本文标题:Javascript: How to pass an array with specific index to a function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744144102a2592755.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论