Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - Why can't we have return in the ternary operator?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...