[英]javascript findIndex callback arguments
I'm new to javascript. 我是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. 我了解到可以使用findIndex遍历数组。 But it seems that findIndex only accept three arguments: element, index and array. 但是似乎findIndex只接受三个参数:元素,索引和数组。 What if I want change the object that is used to be compared. 如果要更改用于比较的对象该怎么办。
For example, I want for find the index of string 'b'
in array ['a','b','c']
, 例如,我要在数组['a','b','c']
查找字符串'b'
的索引,
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 但是我如何传递'b'
作为可以更改为回调函数的参数
Thanks 谢谢
What about indexOf
function? 那indexOf
函数呢? 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 comparing strings. 注意:正如已经建议的,在比较字符串时使用indexOf
更有意义。 The findIndex
function in combination with a custom callback is there for more sophisticated search, eg when dealing with complex structured objects. 结合了自定义回调的findIndex
函数可用于更复杂的搜索,例如在处理复杂的结构化对象时。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.