[英]Most efficient way to search array of object values
I have an onChange function that is called each time a user enters something into a text field. 我有一个onChange函数,每次用户在文本字段中输入内容时都会调用该函数。 The idea is to autocomplete or provide a list of options that contain the text the user has entered, and let them choose from the returned options.
想法是自动完成或提供包含用户输入的文本的选项列表,并让他们从返回的选项中进行选择。 Here is what I have:
这是我所拥有的:
dataSet.filter(option => option.label.toLowerCase().indexOf(input.toLowerCase()) !== -1);
dataSet would look something like this, and could have thousands of elements: dataSet看起来像这样,并且可能包含数千个元素:
[
{
label: "I'm typing this",
value: "1234567890"
},
]
What would be a better, more efficient approach, without getting too crazy? 在不变得太疯狂的情况下,什么是更好,更有效的方法?
You can use debounce as explained in this post for that. 您可以按照本文中的说明使用防抖动功能 。
// Returns a function, that, as long as it continues to be invoked, will not be triggered.
//返回一个函数,只要该函数继续被调用就不会被触发。 The function will be called after it stops being called for N milliseconds.
该函数将在停止调用N毫秒后被调用。 If
immediate
is passed, trigger the function on the leading edge, instead of the trailing.如果通过了
immediate
,则在前沿而不是尾随触发函数。
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
You can benefit from it like- Instead of calling onChange
on every keystroke it will call only after a certain milliseconds have passed which you can set in the debounce function. 您可以像从中受益一样-它不会在每次按键时都调用
onChange
,而是仅在经过一定的毫秒后调用,您可以在debounce函数中进行设置。
And you can use it like 你可以像这样使用它
var myEfficientFn = debounce(onChange, 400);
So if the user have stopped typing for 400ms than only it will call the onChange
function instead of in every keystroke. 因此,如果用户停止键入400毫秒,则只会调用
onChange
函数,而不是每次击键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.