为什么我们不能在三元运算符中返回? [英] Why can't we have return in the ternary operator?

查看:85
本文介绍了为什么我们不能在三元运算符中返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个简单的form,我想检查form是否已更改.如果更改了submit,则其他方法阻止了表单提交,因此我使用return,而不是使用if-else语句,而是尝试使用ternary operation,但是很遗憾,我遇到了错误 Uncaught SyntaxError: Unexpected token return 不明白为什么会出现这个错误?三元运算仅用于分配吗?在这部分上不确定.下面只是我尝试做的一个示例.

Say I've a simple form and I want to check whether form has changed or not. If its changed submit it else prevent form submission, so I used return and instead of using if-else statement I tried to use ternary operation but unfortunately I was hit with error Uncaught SyntaxError: Unexpected token return but I did not understand why this error? Is ternary operation only used to assign? Not sure on this part. Below is just a sample of what I was trying to do.

var form_original_data = $("#frmProfile").serialize();

$("#frmProfile").on('submit', function(e) {
  e.preventDefault();
  $("#frmProfile").serialize() != form_original_data ? $("body").append('changed') : return;
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frmProfile">
  <input type="text" value="name" />
  <input type="submit" value="Go" />
</form>

推荐答案

三元运算符求值一个表达式,并且表达式不能包含return语句(如果将表达式分配给变量,该表达式的行为如何?) .但是,您很可能会返回三元运算符的结果,即return condition? returnValue1 : returnValue2;

The ternary operator evaluates to an expression and expressions can't contain a return statement (how would that behave if you were to assign the expression to a variable?). However, you could very well return the result of a ternary operator, i.e. return condition? returnValue1 : returnValue2;

关于您的特定观点,我不明白您为什么要返回.看起来您仅在满足条件时才尝试做某事.一个简单的if语句可能在那里就足够了.

On your specific point, I don't see why you would like to return. It looks like you're trying to do something only if a condition is fulfilled. A simple if statement would probably be more adequate there.

这篇关于为什么我们不能在三元运算符中返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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