问题描述
我正在使用这个 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))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)