【问题标题】:string objects comparison always returning false字符串对象比较总是返回 false
【发布时间】:2013-12-06 21:38:48
【问题描述】:

这是我正在执行的代码:

filterIssues: function(objectKey, text){
    var view = this;
    var keys = objectKey.split(".");
    var attributeKey = keys[0];
    var attributeName;
    if (keys.length > 1){
        attributeName = keys[1];
    }
    view.issues.each(function(issue){
        var value = issue.get(attributeKey);
        console.log(text);

        if (value === undefined || value === null){
            issue.trigger("hide");
            return;
        }

        if (attributeName !== undefined){
            value = value[attributeName];
        }

        if(value !== undefined){
            var matchedText = value.substring(0, text.length - 1);
            if ( matchedText === text){
                issue.trigger("show");
                console.log(value);  
                return;     
            }
        }
        issue.trigger("hide");
    });
}     

matchedText == text 总是返回 false

这是我在玩控制台时得到的:

> matchedText
"sande"
> text
"sande"
> typeof(text)
"string"
> typeof(matchedText)
"string"
> matchedText === text
false
> matchedText == text
false

我确实意识到=== 将始终检查两个对象是否相同并且我已阅读 JavaScript equal operations anomaliesJavascript string equality

我忽略的代码有问题吗?

【问题讨论】:

  • 检查matchedText.lengthtext.length
  • issues 是什么类型的对象,issues.each() 传递给函数的是什么(即issue 是什么)? issue.get() 返回什么?
  • 可能是栅栏张贴错误? var matchedText = value.substring(0, text.length - 1); 你试过没有 - 1 吗? matchedText.valueOf() === text.valueOf() 或 with (==) 给你什么?
  • 你检查过 trim();
  • @James matchedText.toString() == text.toString() 返回 false=== 也是如此

标签: javascript


【解决方案1】:

我认为您在滥用subString() 方法。如果您使用subString(),请使用不带-1 的长度。

【讨论】:

  • 我改变了长度,没有-1,还是一样。
  • 使用 length-1 肯定是错误的。子字符串的长度必须与 caparison 为真的文本长度相同,而不是少 1。
  • 好吧,我将代码更改为使用切片而不是子字符串。还是同样的问题。
【解决方案2】:

好吧,我最终发现了问题所在。感谢您的回复,我相信您可能因为缺乏信息而没有找到答案。

问题在于我传递给函数的text 值。 text 最后包含 "",这就是为什么比较不起作用的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2016-12-18
    相关资源
    最近更新 更多