What is this JS syntax? Assignment in expression? (x != null amp;amp; (y = x))(这是什么JS语法?表达式赋值?(x != null amp;amp; (y = x)))
问题描述
我正在使用这个 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
}
编码愉快.
这篇关于这是什么JS语法?表达式赋值?(x != null && (y = x))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:这是什么JS语法?表达式赋值?(x != null && (y = x))


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07