相同类型和相同的单词,但当被问及它们是否相同时仍然​​返回false

时间:2018-05-18 17:35:05

标签: javascript angular

所以我正在使用socket.io开发一个聊天应用程序,我想决定它是我的消息还是别人的消息。我使用的两件事是我从localstorage中检索的全名,以及我发送新消息时从服务器返回的全名。有人知道为什么两者仍然不一样,即使它们都是字符串并且它们都是由相同的单词组成的吗?

isItMyMsg(message){
        console.log(localStorage.getItem('fullName'));
        console.log(message.fullname);
        console.log(localStorage.getItem('fullName') === message.fullName);
        return localStorage.getItem('fullName') === message.fullName
    }

这是我记录结果的截图。两个是来自本地存储和服务器对象的结果,而错误来自我评估它们是否相同时。我期待它返回TRUE,但我得到了一个FALSE

enter image description here

1 个答案:

答案 0 :(得分:6)

试试这个: 1 - 检查是否有某些额外的空格,所以:

const first = localStorage.getItem('fullName').trim();
const second = message.fullName.trim();

然后做:

console.log(first === second);

如果不起作用,请尝试:

const first = localStorage.getItem('fullName').trim().toLowerCase();
const second = message.fullname.trim().toLowerCase();

查看区分大小写是否有所不同。