(js仅支持第二种)
第一种也是一道面试题!!怎么优化。
1.?? 运算符称为 null 合并运算符,
用于定义可以为 null 值的类型和引用类型的默认值。
如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
string value=null;
string name=value;
if(value==null)
{
name=string.empty;
}
//优化为
name = value??string.Empty;
//或者
name=(value==null) ? value : "";(个人补充)
//是不是上边那个简单点呢(字数少),哈哈。
//string.Empty 可以用""替换
2.三元运算符(js)
因为js数据类型是弱类型的所以才能这么随意
当a为{false,null,undefined, ""(空字符串),和数字0}返回b,否则返回a;
var a=2;
var b="";
a=(a?a:b);
3.三元运算符(c#)
c#中就不能这么随意了,看第一个例子,再举一个例子
int a=10;
int b;
b=(a==10)?a++:a--;