找到你要的答案

Q:Javascript: meaning of || operator while initializing var [duplicate]

Q:JavaScript:意义| |运算符初始化时无功[复制]

This question already has an answer here:

to get information about what key was pressed, I now use following code:

function AddEventListeners() {
    document.getElementById('txtHangman').addEventListener('keypress', TextHangman.bind(this), false);
}

And then the eventhandler function:

function TextHangman(_key) {
    var _keypressed = _key.which || _key.key;
}

The code works and gives me the information I want but I don't understand what the || operator does when initiliazing the var _keypressed. Some explanation would be great.

Thanks!

G

这个问题在这里已经有了答案:

要获取有关按下哪个键的信息,我现在使用以下代码:

function AddEventListeners() {
    document.getElementById('txtHangman').addEventListener('keypress', TextHangman.bind(this), false);
}

然后EventHandler函数:

function TextHangman(_key) {
    var _keypressed = _key.which || _key.key;
}

代码的作品给我的信息我想但我不懂什么| |操作不当initiliazing VaR _keypressed。一些解释将是伟大的。

谢谢!

G

answer1: 回答1:

It means the same as it does everywhere else. It does nothing special when used near a var statement.

If the left hand side evaluates as true (i.e. not 0, undefined, etc), it evaluates as the left hand side.

Otherwise, it evaluates as the right hand side.


Precedence rules means it gets resolved before the assignment.


Essentially the code is the same as:

if (_key.which) {
    var _keypressed = _key.which;
} else {
    var _keypressed = _key.key;
}

它的意思是和其他地方一样。在var语句附近使用没有什么特别之处。

如果左手侧计算为真(即不是0,未定义,等),它计算为左手侧。

否则,它计算为右手边。


优先级规则意味着在赋值前得到解决。


本质上代码是相同的:

if (_key.which) {
    var _keypressed = _key.which;
} else {
    var _keypressed = _key.key;
}
answer2: 回答2:

It provides a fallback to the var. If the first option is false, null or undefined, the var will be set with the second value

它提供了一个“兜底”的变种,如果第一个选择是错误的,无效的或未定义的变量,将第二值

answer3: 回答3:

This means when there is any falsy value like null or undefined or 0 in _key.which then it should be initialized with _key.key.

You can see it as shortcut for:

var _keypressed = _key.which;
if (!_keypressed) {
    _keypressed = _key.key;
}

这意味着,当有任何falsy值如空或未定义或0 _key.which就应该初始化_key.key。

你可以看到它作为捷径:

var _keypressed = _key.which;
if (!_keypressed) {
    _keypressed = _key.key;
}
javascript  keypress  operator-keyword