1

The javascript void statement evaluates an expression, and returns the undefined value. This is useful because the global variable undefined can be redefined, but why does it evaluate an en expression? Most people just use 0, as in

void 0;
void(0);

Looking at Raghu's answer, the documentation says

This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.

But can you give me an example where you can't just put void(0) in the location where the value ùndefined` is desired, and evaluate the expression with side effects on another line?

4

2 回答 2

2

运算符的主要用途void是(或者曾经是,因为今天您可能更愿意使用事件处理程序)在单击带有javascript:URL 的链接时防止任何导航。此 javascript 函数返回时不会发生导航undefinedvoid操作员通常是实现这一目标的最短途径。

例子

<a href="javascript: void console.log('click') ">log click to console</a>

或者,更一般的

<a href="javascript: void doSomething() ">do something</a>

正如在这个小提琴中看到的

于 2013-09-23T23:45:44.490 回答
1

标准文档应该有助于理解为什么它作为一个表达式进行评估,以及大多数人在哪里以及为什么使用它

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

于 2013-09-23T23:23:24.790 回答