JavaScript表达式,括号内用逗号分隔 [英] JavaScript expressions, comma delimited within parentheses

查看:80
本文介绍了JavaScript表达式,括号内用逗号分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'use strict';

(true, false, 1);

括号是否在多个组成表达式中创建一个表达式?

Do the parentheses create a single expression out of multiple constituent expressions?

我以前没有看过这种语法.

I haven't seen this syntax before.

引起兴趣的原始代码:

function AddWatermark(controlName, defaultValue, cssValue) {
    document.getElementById(controlName).value == "" 
    && 
    (document.getElementById(controlName).value = defaultValue, document.getElementById(controlName).className = cssValue); //I am interested in this syntax on the RHS of the logical AND operator
}

推荐答案

在某些编程语言(包括c ++和js)中,逗号运算符代表评估所有用逗号分隔的表达式并返回最后一个".例如:

In some programming languages (including c++ and js), the comma operator stands for "Evaluate all the expressions separated by commas and return the last one". For example:

var x = (true, false, 1);
console.log(x) // 1

这是另一个向您展示表达式被求值的方法:

Here's another one to show you that expressions are evaluated:

var i = 0;
var j = 0;
var x = (i++, j--);
console.log(i, j, x) // 1 -1 0

函数 AddWaterMark 本质上可以重写为:

The function AddWaterMark essentially can be rewritten as:

function AddWatermark(controlName, defaultValue, cssValue) {
    if (document.getElementById(controlName).value == "") { 
        document.getElementById(controlName).value = defaultValue;    
        document.getElementById(controlName).className = cssValue;
    }
}

这篇关于JavaScript表达式,括号内用逗号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆