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))
				
        
 
            
        基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
 - WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
 - Node.js 有没有好的索引/搜索引擎? 2022-01-01
 - 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
 - jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
 - 什么是不使用 jQuery 的经验技术原因? 2022-01-01
 - 如何使用 CSS 显示和隐藏 div? 2022-01-01
 - 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
 - Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
 - 每次设置弹出窗口的焦点 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				