简体   繁体   English

Javascript-Array.prototype.find是否可以使用参数来搜索

[英]Javascript - can Array.prototype.find take a parameter to search for

I am looking at the documentation here but can not find what I am looking for. 我在这里查看文档但找不到我想要的东西。

What I would like to achieve is something like this: 我想要实现的是这样的:

 var valueToSearchFor = "something"

 function SearchArray(currentIndex, valueToSearchFor){
    return currentIndex.PropertyName === valueToSearchFor;
 }

 var attribute = myArray.find(SearchArray(valueToSearchFor));

rather than: 而不是:

 var valueToSearchFor = "something"

 function SearchArray(currentIndex){
    return currentIndex.PropertyName === valueToSearchFor;
 }

 var attribute = myArray.find(SearchArray);

In my case the valueToSearchFor is not thread safe. 就我而言,valueToSearchFor不是线程安全的。 Am I missing something? 我想念什么吗?

I'm not sure what you mean by: 我不确定您的意思是:

in my case the valueToSearchFor is not thread safe 就我而言,valueToSearchFor不是线程安全的

But regardless, you can still achieve this kind of functionality with currying: 但是无论如何,您仍然可以通过以下方式实现这种功能:

var valueToSearchFor = "something";

function createSearchArray (valueToSearchFor) {
  return function (currentIndex) {
    return currentIndex.PropertyName === valueToSearchFor;
  }
}

var attribute = myArray.find(createSearchArray(valueToSearchFor));

The idea here is to create the function you're looking for using your valueToSearchFor variable. 这里的想法是使用valueToSearchFor变量创建您要查找的函数。 We then return this function to .find() . 然后,我们将此函数返回到.find()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM