javascript - 此条目存在检查中可能出现什么问题?

标签 javascript

我的逻辑可能有什么问题? 如果我检查 (this.holdExists(x,y) != false) ,它会在任何情况下添加条目,或者如果我检查 (this.holdExists) 则根本不添加条目(x,y) == true).

    //check if the hold with coordinates x,y already exists
    holdExists: function(x,y) {
        var precision = 0.01;
        holds.forEach(function(obj) {

            if ( (Math.abs(x - obj.x) < precision)
            || (Math.abs(y - obj.y) < precision) ) {
                console.log('Already exists!');
                return true
            } 
            return false
        });
    },

    // add hold by coordinates only
    addCoordHold: function(x,y) {
        if (this.holdExists(x,y) == true) {
            var h = Hold(x,y);
            holds.push(h);
            console.log('added\n', x,y);
        } else {
            console.log('A hold already exists!');
        }
    },

最佳答案

您正在从传递给 forEach 的迭代器函数返回值,但 forEach 并不关心这些返回值,并且它们与返回无关holdExists 函数的值,正如您所定义的,它始终是未定义

您的意思可能是:

holdExists: function(x,y) {
    var precision = 0.01;
    var rv = false;
    holds.some(function(obj) {

        if ( (Math.abs(x - obj.x) < precision)
        || (Math.abs(y - obj.y) < precision) ) {
            console.log('Already exists!');
            rv = true;
            return true;
        } 
    });
    return rv;
},

这做了几件事:

  1. 它声明一个变量 rv,用作 holdExists 函数的返回值。

  2. 它从 forEach 切换到 some,以便您可以提前结束迭代(forEach 将始终循环所有元素)。

  3. 如果找到匹配项,它会将 rv 设置为 true

  4. 如果找到匹配项,它会停止 some 循环。

  5. 它为 holdExists 函数设置返回值。

关于javascript - 此条目存在检查中可能出现什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461184/

相关文章:

java - jsp servlet嵌入jetty示例代码

javascript - 为什么我的 javascript onclick 事件没有在第一次点击时触发?

javascript - 将脚本文件附加到网站

javascript - 更改 anchor 标记中引用的图像大小

javascript - 在 JavaScript 中反转链表的策略

javascript - 如何使用 jQuery 在 HTML 选择中突出显示某些选项

javascript - jQuery.data() : set values from php

javascript - 是否可以将 Google 的 Web Speech API 与非 Web 应用程序结合使用?

javascript - jQuery AJAX 和 JSON 性能查询

javascript - 魔方加扰算法 - JavaScript