首页 > 解决方案 > Javascript 警告:“^”和“>>>”非混合运算符的意外混合

问题描述

我最近将此哈希函数集成到我的 react web 应用程序中,代码如下:

const cyrb53 = function(str, seed = 0) {
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for (let i = 0, ch; i < str.length; i++) {
        ch = str.charCodeAt(i);
        h1 = Math.imul(h1 ^ ch, 2654435761);
        h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1 = Math.imul(h1 ^ h1>>>16, 2246822507) ^ Math.imul(h2 ^ h2>>>13, 3266489909);
    h2 = Math.imul(h2 ^ h2>>>16, 2246822507) ^ Math.imul(h1 ^ h1>>>13, 3266489909);
    return 4294967296 * (2097151 & h2) + (h1>>>0);
};

我对代码所做的一项更改是我已将其放在一个 utils 文件中,以便该函数可以被多个组件调用。这是我的细微变化:

export function cyrb53(str, seed = 0) { // <- this is the only change I made to integrate this within my apps architecture
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for (let i = 0, ch; i < str.length; i++) {
        ch = str.charCodeAt(i);
        h1 = Math.imul(h1 ^ ch, 2654435761);
        h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1 = Math.imul(h1 ^ h1>>>16, 2246822507) ^ Math.imul(h2 ^ h2>>>13, 3266489909);
    h2 = Math.imul(h2 ^ h2>>>16, 2246822507) ^ Math.imul(h1 ^ h1>>>13, 3266489909);
    return 4294967296 * (2097151 & h2) + (h1>>>0);
};

我在 Firefox 浏览器控制台中收到以下错误:

  Line 95:23:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 95:27:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 95:61:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 95:65:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 96:23:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 96:27:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 96:61:  Unexpected mix of '^' and '>>>'  no-mixed-operators
  Line 96:65:  Unexpected mix of '^' and '>>>'  no-mixed-operators

查看W3 docs,我知道^and>>>运算符用于字节的数学运算。尽管如此,我对javascript中的字节数学并不熟悉。解决此警告的正确方法是什么?

编辑:

接受的答案链接了另一个答案,这被标记为重复,但这个主题略有不同。我问,“我的 Javascript 代码(不是 JSX)发生了什么”,答案是“这实际上是一个 eslint 警告——不是 Javascript——这是一个解决方案。”

标签: javascriptreactjsbinary

解决方案


这不是 javascript 错误,而是 eslint 警告。

请参阅此答案以消除警告。


带有解决方案的代码(使用括号):

export function cyrb53(str, seed = 0) {
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for (let i = 0, ch; i < str.length; i++) {
        ch = str.charCodeAt(i);
        h1 = Math.imul(h1 ^ ch, 2654435761);
        h2 = Math.imul(h2 ^ ch, 1597334677);
    }
    h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909); // <- added parentheses here
    h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909); // <- and added parentheses here; its not much but it is honest work
    return 4294967296 * (2097151 & h2) + (h1>>>0);
};

推荐阅读