0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

今回は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)-制御式

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?