Help us understand the problem. What is going on with this article?

三項演算子の説明と三項演算子の例題

今回はJavaScriptで使われてる三項演算子の説明と、HTML上で入力した数字が奇数か偶数かを判断するページを作ってみます。

三項演算子とは?

「?」と「:」を組見合わせて、if~else文のような処理を簡略化したものです。

書き方

条件式?式1:式2

ページの制作

JavaScriptをHTMLに繋げる方法を知ってる前提で説明します。

JavaScriptのソース

function checkEven() {
  var v = document.getElementById("number").value;
  var r = document.getElementById("result");
  if(v.length == 0) {
    r.textContent = "何かの入力値が必要です";
  } else if(isNaN(v)){
    r.textContent = v + "は数字ではありません";
  } else {
    r.textContent = (v%2==0) ? "偶数です":"奇数です";
  }   
}

HTMLのソース

<h1>奇数か偶数かを判断します。</h1>
<input id="number" />
<button onclick="checkEven()">入力判定</button>
<p id="result"></p>

引用 : Dripcoke

初めてのJavascript-(8)-制御式

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away