这是什么JS语法?表达式赋值?(x != null && (y = x))

2022-01-21 00:00:00 syntax conditional javascript

我正在使用这个 JS 插件,我遇到了一些我以前从未见过的语法.我明白它在做什么,但我不确定它为什么会起作用.

I'm working with this JS plugin, and I've encountered some syntax I've never seen before. I understand what it's doing, but I'm not sure why it works.

这是一个例子:

settings.maxId != null && (params.max_id = settings.maxId);

这只是利用条件和单个 = 吗?这是 JS 常用的语法吗?

Is this just taking advantage of conditionals and the single = ? Is this common syntax for JS?

推荐答案

在 JavaScript 中,= 运算符是一个 表达式 并计算分配的值.因为它是一个表达式,它可以在任何允许使用表达式的地方使用即使它会产生副作用.因此:

In JavaScript the = operator is an expression and evaluates the assigned value. Because it is an expression it can be used anywhere an expression is allowed even though it causes a side-effect. Thus:

settings.maxId != null && (params.max_id = settings.maxId)

意思是:如果 settings.maxId 不为空,那么 (只有这样,因为 && 是 短路) 评估右表达式 (params.max_id = settings.maxId) 进而导致 settings.maxId 的值被分配给 params.max_id.这更清楚写成:

Means: If settings.maxId is not null then (and only then, since && is short circuiting) evaluate the right-expression (params.max_id = settings.maxId) which in turn causes the value of settings.maxId to be assigned to params.max_id. This is much more clearly written as:

if (settings.maxId != null) {
  params.max_id = settings.maxId
}

编码愉快.

相关文章