如何更快地索引 Javascript 中的对象数组?

发布于 2024-11-18 01:11:41 字数 510 浏览 1 评论 0原文

为了构建 JQuery 自动完成所需的字符串数组,我遍历一个对象数组并将其展平为唯一字符串数组。我这样做的方式符合您的预期:

var input = [{prop1:'value1', prop2: 'value2'}];

 $.each(input, function (index, value) {
                $.each(value, function (i, v) {
                    if (v != undefined && v != null && v != '' && ($.inArray(v, keywords) < 0)) {
                        keywords.push(v);
                    }
                });
            });

问题是它对于大型输入集表现不佳,并且在运行时会阻塞 UI。我怎样才能让这个变得更好?

In order to build the array of strings necessary for JQuery autocomplete, I'm traversing an array of objects and flattening it into an array of unique strings. I'm doing this about how you might expect:

var input = [{prop1:'value1', prop2: 'value2'}];

 $.each(input, function (index, value) {
                $.each(value, function (i, v) {
                    if (v != undefined && v != null && v != '' && ($.inArray(v, keywords) < 0)) {
                        keywords.push(v);
                    }
                });
            });

The problem is that it performs poorly for large input sets, and blocks the UI while it's running. How can I make this better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七堇年 2024-11-25 01:11:41

你有一个 O(n^2) 算法。一遍又一遍地查看关键字数组会变得非常慢(正如您所注意到的)。

相反,将关键字保留为对象:

var keywords = {};

    // ... inside your ".each():
    if (v && !keywords[v])
      keywords[v] = true;

请注意,可以通过让 JavaScript 检查其真实性来替换对“v”对未定义、null 和空字符串的测试。这并不总是正确的事情,但在这里没问题。

如果您愿意,您还可以将关键字保存在数组中。只是不要搜索数组来确定是否已经看到关键字。

You've got an O(n^2) algorithm there. Looking through that keywords array over and over again is going to get really slow (as you've noticed).

Instead, keep the keywords as an object:

var keywords = {};

    // ... inside your ".each():
    if (v && !keywords[v])
      keywords[v] = true;

Note that your tests of "v" against undefined, null, and the empty string can be replaced by letting JavaScript check it's truthiness. That's not always the right thing, but it's fine here.

You can also keep the keywords in an array, if you like. Just don't search the array to determine whether a keyword has been seen yet.

找个人就嫁了吧 2024-11-25 01:11:41

我认为你正在尝试解决错误的问题,

为什么你的自动建议列表如此之大以至于 javascript 表现不佳?只需将前 10 条自动建议发送给客户就可以了

i think you're trying to fix wrong problem

why is your autosuggestion list so big that javascript performs poorly? just send top 10 autosuggestions to client and you'll be fine

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文