admin管理员组文章数量:1434960
I'm new to javascript.
I'm trying to find the index of a specific element in an array. I read about that I can use findIndex to loop through an array. But it seems that findIndex only accept three arguments: element, index and array. What if I want change the object that is used to be pared.
For example, I want for find the index of string 'b'
in array ['a','b','c']
,
var position = ['a','b','c'].findIndex(function(element, index, array){return element==='b'})
but how do I pass 'b'
as parameters that I can change to callback function
Thanks
I'm new to javascript.
I'm trying to find the index of a specific element in an array. I read about that I can use findIndex to loop through an array. But it seems that findIndex only accept three arguments: element, index and array. What if I want change the object that is used to be pared.
For example, I want for find the index of string 'b'
in array ['a','b','c']
,
var position = ['a','b','c'].findIndex(function(element, index, array){return element==='b'})
but how do I pass 'b'
as parameters that I can change to callback function
Thanks
Share Improve this question edited Jul 27, 2017 at 12:24 Talha Awan 4,6194 gold badges26 silver badges40 bronze badges asked Jul 27, 2017 at 11:19 X.ZX.Z 1,1482 gold badges11 silver badges16 bronze badges 1-
1
"findIndex only accept three arguments" not really.
findIndex
accepts 2 arguments: callback and optional context. It is a callback that is being called with 3 arguments. – Yury Tarabanko Commented Jul 27, 2017 at 11:27
3 Answers
Reset to default 4What about indexOf
function? You just have to pass one argument, as searched element.
let arr = ['a','b','c'];
console.log(arr.indexOf('b'));
You can define the wanted character from the outside context inside the callback function:
var wantedChar = 'c';
var position = ['a','b','c'].findIndex(function(element, index, array){return element===wantedChar})
console.log(position);
By doing so, you can wrap all that up in a function:
var findPos = function(arr, char){
return arr.findIndex(function(element, index, array){return element===char});
}
console.log(findPos(['a','b','c'], 'c'));
Note: as already suggested, it makes more sense to use indexOf
when just paring strings. The findIndex
function in bination with a custom callback is there for more sophisticated search, e.g. when dealing with plex structured objects.
function getPosition(){
var position = ["a","b","c"];
var a = position.indexOf("b");
document.getElementById("demo").innerHTML = a;
}
<button onclick="getPosition()">button</button>
<p id="demo"></p>
本文标签: javascript findIndex callback argumentsStack Overflow
版权声明:本文标题:javascript findIndex callback arguments - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745629506a2667182.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论