javascript - 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——这是一个解决方案。”
解决方案
这不是 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);
};
推荐阅读
- php - 将使用 PHP 创建的 csv 文件导入 Excel 时,如何在数字字符串值中保留前导零?
- php - 如何在 Laravel 中不使用 foreach 存储请求数组?
- javascript - 在Angular的子组件中单击按钮时如何为父组件属性设置值
- java - 如何以 AB123 --> AB 123 格式拆分字符串?爪哇
- javascript - 如何删除谷歌图表中的工具提示
- ag-grid - 农业网格的最佳自动化测试套件是什么?
- oracle - 如何在不显示密码的情况下从 unix 连接 oracle 数据库
- gcc - GCC 的 ffast-math 是否具有跨平台或编译器版本的一致性保证?
- jquery - 为什么 JQuery 需要时间来加载?
- javascript - 移动设备上输入值更改的正确事件是什么?