From abbf5910d201761681df167db2523f140ec39de2 Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sun, 18 Jul 2021 16:56:59 +0900 Subject: Learn/Getting_started_with_the_web/JavaScript_basics を更新 (#1476) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Learn/Getting_started_with_the_web/JavaScript_basics を更新 - 2021/07/10 時点の英語版に同期 - conflicting 版は未翻訳版なので削除 * conflicting/Web/JavaScript/Reference/Operators を削除 正規版に統合されているため、conflicting 版を削除。 併せて、以前削除した別な conflicting 版の履歴を削除。 --- files/ja/_redirects.txt | 8 +- files/ja/_wikihistory.json | 31 --- .../javascript_basics/index.html | 304 --------------------- .../web/javascript/reference/operators/index.html | 231 ---------------- .../javascript_basics/index.html | 222 ++++++++------- files/ja/web/html/element/hgroup/index.html | 44 +-- .../reference/global_objects/date/index.html | 2 +- 7 files changed, 148 insertions(+), 694 deletions(-) delete mode 100644 files/ja/conflicting/learn/getting_started_with_the_web/javascript_basics/index.html delete mode 100644 files/ja/conflicting/web/javascript/reference/operators/index.html (limited to 'files/ja') diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 29deb06c2f..2fa765b24b 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -2909,7 +2909,7 @@ /ja/docs/JavaScript/Reference/Operators/Bitwise_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/JavaScript/Reference/Operators/Comma_Operator /ja/docs/Web/JavaScript/Reference/Operators/Comma_Operator /ja/docs/JavaScript/Reference/Operators/Comma_Operator-redirect-1 /ja/docs/Web/JavaScript/Reference/Operators/Comma_Operator -/ja/docs/JavaScript/Reference/Operators/Comparison_Operators /ja/docs/conflicting/Web/JavaScript/Reference/Operators +/ja/docs/JavaScript/Reference/Operators/Comparison_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/JavaScript/Reference/Operators/Conditional_Operator /ja/docs/Web/JavaScript/Reference/Operators/Conditional_Operator /ja/docs/JavaScript/Reference/Operators/Logical_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/JavaScript/Reference/Operators/Member_Operators /ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors @@ -4580,7 +4580,7 @@ /ja/docs/Web/HTTP/Server-Side_Access_Control /ja/docs/Web/HTTP/CORS /ja/docs/Web/HTTP/X-Frame-Options /ja/docs/Web/HTTP/Headers/X-Frame-Options /ja/docs/Web/JavaScript/Equality_comparisons_and_when_to_use_them /ja/docs/Web/JavaScript/Equality_comparisons_and_sameness -/ja/docs/Web/JavaScript/Getting_Started /ja/docs/conflicting/Learn/Getting_started_with_the_web/JavaScript_basics +/ja/docs/Web/JavaScript/Getting_Started /ja/docs/Learn/Getting_started_with_the_web/JavaScript_basics /ja/docs/Web/JavaScript/Guide/About /ja/docs/Web/JavaScript/Guide/Introduction /ja/docs/Web/JavaScript/Guide/Block_Statement /ja/docs/Web/JavaScript/Guide/Control_flow_and_error_handling /ja/docs/Web/JavaScript/Guide/Class-Based_vs._Prototype-Based_Languages /ja/docs/orphaned/Web/JavaScript/Guide/Class-Based_vs._Prototype-Based_Languages @@ -4813,7 +4813,7 @@ /ja/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/Web/JavaScript/Reference/Operators/Assignment_Operators /ja/docs/Web/JavaScript/Reference/Operators#Assignment_operators /ja/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators /ja/docs/Web/JavaScript/Reference/Operators -/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators /ja/docs/conflicting/Web/JavaScript/Reference/Operators +/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/Web/JavaScript/Reference/Operators/Logical_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/Web/JavaScript/Reference/Operators/Member_Operators /ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors /ja/docs/Web/JavaScript/Reference/Operators/Pipeline_operator /ja/docs/orphaned/Web/JavaScript/Reference/Operators/Pipeline_operator @@ -5409,7 +5409,7 @@ /ja/docs/dummySlug/Reference/Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/dummySlug/Reference/Operators/Assignment_Operators /ja/docs/Web/JavaScript/Reference/Operators#Assignment_operators /ja/docs/dummySlug/Reference/Operators/Comma_Operator /ja/docs/Web/JavaScript/Reference/Operators/Comma_Operator -/ja/docs/dummySlug/Reference/Operators/Comparison_Operators /ja/docs/conflicting/Web/JavaScript/Reference/Operators +/ja/docs/dummySlug/Reference/Operators/Comparison_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/dummySlug/Reference/Operators/Logical_Operators /ja/docs/Web/JavaScript/Reference/Operators /ja/docs/dummySlug/Reference/Operators/Member_Operators /ja/docs/Web/JavaScript/Reference/Operators/Property_Accessors /ja/docs/dummySlug/Reference/Operators/Operator_Precedence /ja/docs/Web/JavaScript/Reference/Operators/Operator_Precedence diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 1d3e84cd70..a2d166f285 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -48159,12 +48159,6 @@ "silverskyvicto" ] }, - "conflicting/Learn/Getting_started_with_the_web/JavaScript_basics": { - "modified": "2019-03-23T23:21:46.830Z", - "contributors": [ - "sunagakazuo" - ] - }, "conflicting/Learn/HTML/Howto/Author_fast-loading_HTML_pages": { "modified": "2020-07-16T22:22:32.832Z", "contributors": [ @@ -48641,31 +48635,6 @@ "electrolysis" ] }, - "conflicting/Web/JavaScript/Reference/Operators": { - "modified": "2020-10-15T21:04:54.922Z", - "contributors": [ - "tbpgr", - "mfuji09", - "yokotay", - "AkihikoTakeda", - "ambi", - "yyss", - "teoli", - "ethertank", - "Potappo" - ] - }, - "conflicting/Web/JavaScript/Reference/Operators_f71733c8e7001a29c3ec40d8522a4aca": { - "modified": "2020-03-12T19:35:34.796Z", - "contributors": [ - "AkihikoTakeda", - "yyss", - "teoli", - "keiskimu", - "ethertank", - "Potappo" - ] - }, "conflicting/tools/Keyboard_shortcuts": { "modified": "2020-07-16T22:34:03.446Z", "contributors": [ diff --git a/files/ja/conflicting/learn/getting_started_with_the_web/javascript_basics/index.html b/files/ja/conflicting/learn/getting_started_with_the_web/javascript_basics/index.html deleted file mode 100644 index bc0542c594..0000000000 --- a/files/ja/conflicting/learn/getting_started_with_the_web/javascript_basics/index.html +++ /dev/null @@ -1,304 +0,0 @@ ---- -title: Getting Started (Javascript Tutorial) -slug: conflicting/Learn/Getting_started_with_the_web/JavaScript_basics -translation_of: Learn/Getting_started_with_the_web/JavaScript_basics -translation_of_original: Web/JavaScript/Getting_Started -original_slug: Web/JavaScript/Getting_Started ---- -

Why JavaScript?

-

JavaScript is a powerful, complicated, and often misunderstood computer language. It enables the rapid development of applications in which users can enter data and view results easily.

-

The primary advantage to JavaScript, which is also known as ECMAScript, centers around the Web browser, thus having the ability to produce the same results on all platforms supported by the browser. The examples on this page, just like Google Maps, run on Linux, Windows, and Mac OS. With the recent growth of numerous JavaScript libraries it is now easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. Unlike the hype around other technologies pushed by various proprietary interests, JavaScript is really the only cross-platform, client-side programming language that is both free and universally adopted.

-

What you should already know

-

JavaScript is a very easy language to start programming with. All you need is a text editor and a Web browser to get started.

-

There are many other technologies that can be integrated into and developed along with JavaScript that are beyond the scope of this document. Don't expect to make a whole application like Google Maps all on your first day!

-

Getting started

-

Getting started with JavaScript is very easy. You don't have to have complicated development programs installed. You don't have to know how to use a shell, program Make, or use a compiler. JavaScript is interpreted by your Web browser. All you have to do is save your program as a text file and then open it up in your Web browser. That's it!

-

JavaScript is a great programming language for introductory computer languages. It allows instant feedback to the new student and teaches them about tools they will likely find useful in their real life. This is in stark contrast to C, C++, and Java which are really only useful for dedicated software developers.

-

Browser compatibility issues

-

There are variations between what functionality is available in the different browsers. Mozilla, Microsoft IE, Apple Safari, and Opera fluctuate in behavior. We intend on documenting these variations. You can mitigate these issues by using the various cross-platform JavaScript APIs that are available. These APIs provide common functionality and hide these browser fluctuations from you.

-

How to try the examples

-

The examples below have some sample code. There are many ways to try these examples out. If you already have your own website, then you should be able to just save these examples as new Web pages on your website.

-

If you do not have your own website, you can save these examples as files on your computer and open them up with the Web browser you are using now. JavaScript is a very easy language to use for beginning programmers for this reason. You don't need a compiler or a development environment; you and your browser are all you need to get started!

-

Example: Catching a mouse click

-

The specifics of event handling (event types, handler registration, propagation, etc.) are too extensive to be fully covered in this simple example. However, this example cannot demonstrate catching a mouse click without delving a little into the JavaScript event system. Just keep in mind that this example will only graze the full details about JavaScript events and that if you wish to go beyond the basic capabilities described here, read more about the JavaScript event system.

-

'Mouse' events are a subset of the total events issued by a Web browser in response to user actions. The following is a list of the events emitted in response to a user's mouse action:

- -

Note that in the latest versions of HTML, the inline event handlers, i.e. the ones added as tag attributes, are expected to be all lowercase and that event handlers in script are always all lowercase.

-

The simplest method for capturing these events, to register event handlers - using HTML - is to specify the individual events as attributes for your element. Example:

-
  <span onclick="alert('Hello World!');">Click Here</span>
-

The JavaScript code you wish to execute can be inlined as the attribute value or you can call a function which has been defined in a <script> block within the HTML page:

-
<script type="text/javascript">
-  function clickHandler () {
-     alert ("Hello, World!");
-  }
-</script>
-<span onclick="clickHandler();">Click Here</span>
-

Additionally, the event object which is issued can be captured and referenced, providing the developer with access to specifics about the event such as which object received the event, the event's type, and which mouse button was clicked. Using the inline example again:

-
<script type="text/javascript">
-  function clickHandler(event) {
-    var eType = event.type;
-    /* the following is for compatibility */
-    /* Moz populates the target property of the event object */
-    /* IE populates the srcElement property */
-    var eTarget = event.target || event.srcElement;
-
-    alert( "Captured Event (type=" + eType + ", target=" + eTarget );
-  }
-</script>
-<span onclick="clickHandler(event);">Click Here</span>
-

In addition to registering to receive events in your HTML, you can likewise set the same attributes of any HTMLElement objects generated by your JavaScript. The example below instantiates a span object, appends it to the page body, and registers the span object to receive mouse-over, mouse-out, mouse-down, and mouse-up events.

-
<body></body>
-<script type="text/javascript">
-  function mouseeventHandler(event) {
-    /* The following is for compatibility */
-    /* IE does NOT by default pass the event object */
-    /* obtain a ref to the event if one was not given */
-    if (!event) event = window.event;
-
-    /* obtain event type and target as earlier */
-    var eType = event.type;
-    var eTarget = event.target || event.srcElement;
-    alert(eType +' event on element with id: '+ eTarget.id);
-  }
-
- function onloadHandler () {
-   /* obtain a ref to the 'body' element of the page */
-   var body = document.body;
-   /* create a span element to be clicked */
-   var span = document.createElement('span');
-   span.id = 'ExampleSpan';
-   span.appendChild(document.createTextNode ('Click Here!'));
-
-   /* register the span object to receive specific mouse events -
-      notice the lowercase of the events but the free choice in the names of the handlers you replace them with.
-   */
-   span.onmousedown = mouseeventHandler;
-   span.onmouseup = mouseeventHandler;
-   span.onmouseover = mouseeventHandler;
-   span.onmouseout = mouseeventHandler;
-
-   /* display the span on the page */
-   body.appendChild(span);
-}
-
-window.onload = onloadHandler; // since we replace the handler, we do NOT have () after the function name
-</script>
-

Example: Catching a keyboard event

-

Similar to the "Catching a mouse event" example above, catching a keyboard event relies on exploring the JavaScript event system. Keyboard events are fired whenever any key is used on the keyboard.

-

The list of available keyboard events emitted in response to a keyboard action is considerably smaller than those available for mouse:

- -

In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g., 'a'), charCode is set to the code of that character, respecting the letter case (i.e., charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode.

-

The simplest method for capturing keyboard events is again to register event handlers within the HTML, specifying the individual events as attributes for your element. Example:

-
  <input type="text" onkeypress="alert ('Hello World!');" />
-
-

As with mouse events, the JavaScript code you wish to execute can be inlined as the attribute value or you can call a function which has been defined in a <script> block within the HTML page:

-
<script type="text/javascript">
-  function keypressHandler() {
-    alert ("Hello, World!");
-  }
-</script>
-
-<input onkeypress="keypressHandler();" />
-
-

Capturing the event and referencing the target (i.e., the actual key that was pressed) is achieved in a similar way to mouse events:

-
<script type="text/javascript">
-  function keypressHandler(evt) {
-      var eType = evt.type; // Will return "keypress" as the event type
-      /* here we again need to use a cross browser method
-         mozilla based browsers return which and others keyCode.
-         The Conditional operator or ternary is a good choice */
-      var keyCode = evt.which?evt.which:evt.keyCode;
-      var eCode = 'keyCode is ' + keyCode;
-      var eChar = 'charCode is ' + String.fromCharCode(keyCode); // or evt.charCode
-      alert ("Captured Event (type=" + eType + ", key Unicode value=" + eCode + ", ASCII value=" + eChar + ")");
-   }
-</script>
-<input onkeypress="keypressHandler(event);" />
-

Capturing any key event from the page can be done by registering the event at the document level and handling it in a function:

-
<script type="text/javascript">
-  document.onkeypress = keypressHandler(event);
-  document.onkeydown = keypressHandle(event);
-  document.onkeyup =keypressHandle(event)
-
-</script>
-

Here is a complete example that shows key event handling:

-
<!DOCTYPE html>
-<html>
-<head>
-  <script>
-    var metaChar = false;
-    var exampleKey = 16;
-    function keyEvent(event) {
-      var key = event.keyCode || event.which; // alternative to ternary - if there is no keyCode, use which
-      var keychar = String.fromCharCode(key);
-      if (key==exampleKey) { metaChar = true; }
-      if (key!=exampleKey) {
-         if (metaChar) {
-            alert("Combination of metaKey + " + keychar)
-            metaChar = false;
-         } else { alert("Key pressed " + key); }
-      }
-    }
-    function metaKeyUp (event) {
-      var key = event.keyCode || event.which;
-      if (key==exampleKey) { metaChar = false; }
-    }
-  </script>
-</head>
-<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
-    Try pressing any key!
-</body>
-</html>
-

Browser bugs and quirks

-

The two properties made available through the key events are keyCode and charCode. In simple terms, keyCode refers to the actual keyboard key that was pressed by the user, while charCode is intended to return that key's ASCII value. These two values may not necessarily be the same; for instance, a lower case 'a' and an upper case 'A' have the same keyCode, because the user presses the same key, but a different charCode because the resulting character is different.

-

The way in which browsers interpret the charCode is not a consistently-applied process. For example, Internet Explorer and Opera do not support charCode. However, they give the character information in keyCode, but only onkeypress. Onkeydown and onkeyup keyCode contain key information. Firefox uses a different word, "which", to distinguish the character.

-

Refer to the Mozilla Documentation on Keyboard Events for a further treatment of keyboard events.

-

{{ draft() }}

-

Example: Dragging images around

-

The following example allows moving the image of Firefox around the page:

-
<!DOCTYPE html>
-<html>
-<head>
-<style type='text/css'>
-img { position: absolute; }
-</style>
-
-<script type='text/javascript'>
-window.onload = function() {
-
-  movMeId = document.getElementById("ImgMov");
-  movMeId.style.top = "80px";
-  movMeId.style.left = "80px";
-
-  document.onmousedown = coordinates;
-  document.onmouseup = mouseup;
-
-  function coordinates(e) {
-    if (e == null) { e = window.event;}
-
-    // e.srcElement holds the target element in IE, whereas e.target holds the target element in Firefox
-    // Both properties return the HTML element the event took place on.
-
-    var sender = (typeof( window.event ) != "undefined" ) ? e.srcElement : e.target;
-
-    if (sender.id=="ImgMov") {
-      mouseover = true;
-      pleft = parseInt(movMeId.style.left);
-      ptop = parseInt(movMeId.style.top);
-      xcoor = e.clientX;
-      ycoor = e.clientY;
-      document.onmousemove = moveImage;
-      return false;
-    } else {
-        return false;
-    }
-  }
-
-  function moveImage(e) {
-    if (e == null) { e = window.event; }
-    movMeId.style.left = pleft+e.clientX-xcoor+"px";
-    movMeId.style.top = ptop+e.clientY-ycoor+"px";
-    return false;
-  }
-
-  function mouseup(e) {
-    document.onmousemove = null;
-  }
-}
-</script>
-</head>
-
-<body>
-  <img id="ImgMov" src="http://placehold.it/100x100&text=JS" width="64" height="64" />
-  <p>Drag and drop around the image in this page.</p>
-</body>
-
-</html>
-

Example: Resizing things

-
- Example of resizing an image (the actual image is not resized, only the image's rendering.) -
  <!DOCTYPE html>
-  <html>
-    <head>
-      <style>
-        #resizeImage {
-          margin-left: 100px;
-        }
-      </style>
-      <script>
-      window.onload = function() {
-
-        var resizeId = document.getElementById("resizeImage");
-        var resizeStartCoordsX,
-            resizeStartCoordsY,
-            resizeEndCoordsX,
-            resizeEndCoordsY;
-
-        var resizeEndCoords;
-        var resizing = false;
-
-        document.onmousedown = coordinatesMousedown;
-        document.onmouseup = coordinatesMouseup;
-
-        function coordinatesMousedown(e) {
-          if (e == null) {
-            e = window.event;
-          }
-
-          var element = (typeof( window.event ) != 'undefined' ) ? e.srcElement : e.target;
-
-          if (element.id == "resizeImage") {
-            resizing = true;
-            resizeStartCoordsX = e.clientX;
-            resizeStartCoordsY = e.clientY;
-          }
-          return false;
-        }
-
-        function coordinatesMouseup(e) {
-          if (e == null) {
-            e = window.event;
-          }
-
-          if (resizing === true) {
-            var currentImageWidth = parseInt(resizeId.width);
-            var currentImageHeight = parseInt(resizeId.height);
-
-            resizeEndCoordsX = e.clientX;
-            resizeEndCoordsY = e.clientY;
-
-            resizeId.style.height = currentImageHeight - (resizeStartCoordsY - resizeEndCoordsY) + 'px';
-            resizeId.style.width = currentImageWidth - (resizeStartCoordsX - resizeEndCoordsX) + 'px';
-
-            resizing = false;
-          }
-          return false;
-        }
-      }
-      </script>
-    </head>
-
-    <body>
-      <img id="resizeImage" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png"
-width="64" height="64" />
-      <p>Click on the image and drag for resizing.</p>
-    </body>
-
-  </html>
-
-

Example: Drawing Lines

-

{{todo("Need Content. Or, remove headline")}}

diff --git a/files/ja/conflicting/web/javascript/reference/operators/index.html b/files/ja/conflicting/web/javascript/reference/operators/index.html deleted file mode 100644 index a32c321159..0000000000 --- a/files/ja/conflicting/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: 比較演算子 -slug: conflicting/Web/JavaScript/Reference/Operators -tags: - - JavaScript - - Operator - - Reference - - 演算子 -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Comparison_Operators -original_slug: Web/JavaScript/Reference/Operators/Comparison_Operators ---- -
{{jsSidebar("Operators")}}
- -

JavaScript には、厳密な比較と型変換の比較の両方があります。厳密な比較 (例: ===) は、オペランドが同じ型で、内容も一致している場合にのみ真になります。もっとよく使用される抽象的な比較 (例: ==) は、比較する前にオペランドを同じ型に変換します。抽象的な関係比較 (例: <=) では、比較前にまずオペランドがプリミティブ型に変換され、それから同じ型に変換されます。

- -

文字列は Unicode 値を使用した標準的な辞書順に基づいて比較されます。

- -
{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}
- -
-
{{EmbedInteractiveExample("pages/js/expressions-strict-equality.html")}}
-
- -
- - - -

比較の機能は以下のとおりです。

- - - -

等価演算子

- -

等価 (==)

- -

等価演算子は、2 つのオペランドが同じ型でないならばオペランドを変換して、それから厳密な比較を行います。両方のオペランドがオブジェクトならば、 JavaScript は内部参照を比較するので、オペランドがメモリ内の同じオブジェクトを参照するときに等しくなります。

- -

構文

- -
x == y
-
- -

- -
1    ==  1         // true
-'1'  ==  1         // true
-1    == '1'        // true
-0    == false      // true
-0    == null       // false
-var object1 = {'key': 'value'}, object2 = {'key': 'value'};
-object1 == object2 // false
-0    == undefined  // false
-null == undefined  // true
-
- -

不等価 (!=)

- -

不等価演算子は、オペランド同士が等しくないならば真を返します。2 つのオペランドが同じ型でないならば、JavaScript は適切な型にオペランドを変換して比較しようとします。両方のオペランドがオブジェクトならば、JavaScript は内部参照を比較するので、オペランドがメモリ内の異なるオブジェクトを参照するときには等しくなりません。

- -

構文

- -
x != y
- -

- -
1 !=   2     // true
-1 !=  '1'    // false
-1 !=  "1"    // false
-1 !=  true   // false
-0 !=  false  // false
-
- -

一致 / 厳密等価 (===)

- -

厳密等価演算子は、型変換なしでオペランド同士が (上に示した通り) 厳密に等しければ真を返します。

- -

構文

- -
x === y
- -

- -
3 === 3   // true
-3 === '3' // false
-var object1 = {'key': 'value'}, object2 = {'key': 'value'};
-object1 === object2 //false
- -

不一致 / 厳密不等価 (!==)

- -

厳密不等価演算子は、オペランド同士が等しくないか、型が等しくない、あるいはその両方ならば真を返します。

- -

構文

- -
x !== y
- -

- -
3 !== '3' // true
-4 !== 3   // true
-
- -

関係演算子

- -

これらの演算子のそれぞれは、比較が行われる前に、そのオペランドをプリミティブに{{Glossary("Type_coercion", "型強制")}}します。両方とも文字列として終わる場合は、辞書順で比較され、そうでない場合は数値に変換されて比較されます。 NaN との比較は常に false を生み出します。

- -

大なり演算子 (>)

- -

大なり演算子は、左オペランドが右オペランドより大きければ、真を返します。

- -

構文

- -
x > y
- -

- -
4 > 3 // true
-
- -

大なりイコール演算子 (>=)

- -

大なりイコール演算子は、左オペランドが右オペランド以上ならば、真を返します。

- -

構文

- -
 x >= y
- -

- -
4 >= 3 // true
-3 >= 3 // true
-
- -

小なり演算子 (<)

- -

小なり演算子は、左オペランドが右オペランドより小さければ、真を返します。

- -

構文

- -
 x < y
- -

- -
3 < 4 // true
-
- -

小なりイコール演算子 (<=)

- -

小なりイコール演算子は、左オペランドが右オペランド以下ならば、真を返します。

- -

構文

- -
 x <= y
- -

- -
3 <= 4 // true
-3 <= 3 // true
-
- -

等価演算子の使用

- -

標準等価演算子 (==!=) は 2 つのオペランドの比較に抽象的等価比較アルゴリズムを使用します。オペランドの型が異なる場合は、比較を行う前にそれらを同じ型に変換しようとします。例えば 5 == '5' という式では、比較を行う前に右オペランドの文字列を数値に変換します。

- -

厳密等価演算子 (===!==) は厳密等価比較アルゴリズムを使用して、オペランドの型が同一かどうかに関する比較も行います。オペランドの型が異なれば、例えば 5'5' の比較では、同一性比較 5 !== '5'true と評価され、 5 === '5' のチェックは false 評価されます。

- -

厳密等価演算子を使うのは、オペランドが特定の型の特定の値でなければならない場合、言い換えればオペランドの正確な型が重要な場合です。それ以外では、2 つのオペランドが同じ型でなくても比較が可能になる、標準的な等価演算子を使えます。

- -

比較に型の変換が関わるとき (つまり厳密でない比較のとき)、 JavaScript は以下のように {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 型のオペランドを変換します。

- - - -
メモ: String オブジェクトはオブジェクト型であり、文字列型ではありません! String オブジェクトはほとんど使わないので、次の結果に驚くかもしれません。
- -
// 両方のオペランドが文字列型 (すなわちプリミティブな文字列) なので、true
-'foo' === 'foo'
-
-var a = new String('foo');
-var b = new String('foo');
-
-// a と b はオブジェクト型で、異なるオブジェクトを参照しているので、false
-a == b
-
-// a と b はオブジェクト型で、異なるオブジェクトを参照しているので、false
-a === b
-
-// a と 'foo' は異なる型で、比較前にオブジェクト (a) は
-// 文字列 'foo' に変換されるので、真
-a == 'foo'
- -

仕様書

- - - - - - - - - - - - - - - -
仕様書
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality Operators')}}
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}
- -

ブラウザーの互換性

- -

{{Compat("javascript.operators.comparison")}}

- -

関連情報

- - diff --git a/files/ja/learn/getting_started_with_the_web/javascript_basics/index.html b/files/ja/learn/getting_started_with_the_web/javascript_basics/index.html index b3d1dc4916..808a7a8371 100644 --- a/files/ja/learn/getting_started_with_the_web/javascript_basics/index.html +++ b/files/ja/learn/getting_started_with_the_web/javascript_basics/index.html @@ -2,12 +2,12 @@ title: JavaScript の基本 slug: Learn/Getting_started_with_the_web/JavaScript_basics tags: + - Beginner + - CodingScripting - JavaScript - Learn - Web - - codescripting - - 'l10n:priority' - - 初心者 + - l10n:priority translation_of: Learn/Getting_started_with_the_web/JavaScript_basics ---
{{LearnSidebar}}
@@ -15,30 +15,30 @@ translation_of: Learn/Getting_started_with_the_web/JavaScript_basics
{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}
-

JavaScript は Web サイトにインタラクティブ機能 (ゲーム、ボタンが押されたときやデータがフォームに入力されたときの反応、動的なスタイルの変更、アニメーションなど) を追加するプログラミング言語です。この記事は、このエキサイティングな言語を始めるのに役立ち、可能性についてのアイディアを提供します。

+

JavaScript はウェブサイトにインタラクティブ機能 (ゲーム、ボタンが押されたときやデータがフォームに入力されたときの反応、動的なスタイルの変更、アニメーションなど) を追加するプログラミング言語です。この記事は、このエキサイティングな言語を始めるのに役立ち、可能性についてのアイディアを提供します。

-

そもそも JavaScript とは何か

+

JavaScript とは何か

-

{{Glossary("JavaScript")}} (略して "JS") は成熟した{{Glossary("Dynamic_programming_language", "動的プログラミング言語")}}であり、{{Glossary("HTML")}} 文書に適用すると、 Web サイトに動的な対話操作を提供できます。Mozilla プロジェクト、Mozilla Foundation、Mozilla Corporation の共同設立者である Brendan Eich によって考案されました。

+

{{Glossary("JavaScript")}} (略して "JS") は成熟した{{Glossary("Dynamic_programming_language", "動的プログラミング言語")}}であり、{{Glossary("HTML")}} 文書に適用すると、ウェブサイトに動的な対話操作を提供できます。Mozilla プロジェクト、Mozilla Foundation、Mozilla Corporation の共同設立者である Brendan Eich によって考案されました。

-

JavaScript の用途は多彩です。小さいものでは、カルーセル、画像ギャラリー、レイアウトの変更、ボタンのクリックに対するレスポンスなどから始めることができます。もっと経験を積むと、ゲーム、2D および 3D のアニメーショングラフィック、包括的なデータベース駆動型アプリケーションなどを作成することができます。

+

JavaScript は汎用性が高く、初心者にもやさしいものです。経験を積めば、ゲーム、 2D や 3D のアニメーション、包括的なデータベース駆動型のアプリなどが作れるようになります。

-

JavaScript はとてもコンパクトですが、一方でとても柔軟性があります。開発者は JavaScript 言語のコアをベースに多種多様なツールを作成し、最小限の労力で膨大な様々な機能を利用できるようにしました。例えば以下のようなものがあります。

+

JavaScript は比較的コンパクトですが、一方でとても柔軟性があります。開発者は JavaScript 言語のコアをベースに多種多様なツールを作成し、最小限の労力で膨大な様々な機能を利用できるようにしました。例えば以下のようなものがあります。

-

この記事は JavaScript の簡単な紹介に留めるべきだと思いますので、現段階では、JavaScript 言語のコアと上記の様々なツールの違いを詳しく話して混乱させることは避けるようにします。それらは、この後に続く詳細、JavaScript 学習エリア、およびMDN の他の部分で詳しく学ぶことができます。

+

コアの JavaScript 言語が上記のツールとどのように違うのか、その詳細を紹介することは、 JavaScript の軽い入門者向けの書籍であるこの記事の範囲外です。詳細は MDN の JavaScript 学習エリアや、 MDN の他の部分で詳しく学ぶことができます。

-

以下では、コア言語のいくつかの側面について紹介します。またブラウザの API 機能についてもいくつか説明します。楽しみましょう!

+

以下では、コア言語のいくつかの側面について紹介します。またブラウザーの API 機能についてもいくつか説明します。楽しみましょう!

-

"Hello world" の例

+

Hello world! の例

-

上記の章は実にエキサイティングに聞こえるかもしれませんが、それもそのはずです — JavaScript は最も活気のある Web 技術の 1 つで、使い始めれば、 Web サイトは力と創造性の新しい次元に入るでしょう。

+

JavaScript は、最も人気のある現代のウェブ技術のひとつです。あなたの JavaScript のスキルが上がれば、あなたのウェブサイトのパワーと創造性は新たな次元に入るでしょう。

しかし、JavaScript を使いこなせるようになるのは HTML や CSS よりも少し難しいです。小さなものから始め、小さく確実な手順で作業を続ける必要があるかもしれません。始めるにあたって、"hello world!" を表示する例 (基本的なプログラミング例の標準) を作りながら、基本的な JavaScript をページに追加する方法を紹介しましょう。

@@ -47,52 +47,54 @@ translation_of: Learn/Getting_started_with_the_web/JavaScript_basics
    -
  1. 最初に、あなたのテストサイトに行って、「scripts」という名前(かぎ括弧は除く)の新しいフォルダを作成してください。それから、作成した scripts フォルダの中で main.js という新しいファイルを作成してください。それを scripts フォルダに保存してください。
  2. -
  3. 次に、 index.html ファイルの </body> 閉じタグの前に新しい行を追加し、以下の新しい要素を追加してください。 -
    <script src="scripts/main.js"></script>
    +
  4. 最初にテストサイトに行き、 scripts という名前の新しいフォルダーを作成してください。それから、 scripts フォルダーの中に main.js という新しいファイルを作成して保存してください。
  5. +
  6. index.html ファイルの </body> 閉じタグの直前に新しい行で、以下の新しい要素を追加してください。 +
    <script src="scripts/main.js"></script>
  7. これは CSS の {{htmlelement("link")}} 要素の時の作業と基本的に同じです。これは JavaScript をページに適用するので、(CSS の時と同じく、ページ上の何に対しても) HTML に影響を与えることができます。
  8. main.js ファイルに次のコードを追加してください。 -
    const myHeading = document.querySelector('h1');
    +  
    const myHeading = document.querySelector('h1');
     myHeading.textContent = 'Hello world!';
  9. -
  10. 最後に、 HTML と JavaScript を書いたファイルを保存したことを確認し、ブラウザで index.html を読み込んでください。
  11. +
  12. 最後に、 HTML と JavaScript を書いたファイルを保存したことを確認し、ブラウザーで index.html を読み込んでください。
-

: {{htmlelement("script")}} 要素を HTML ファイルの末尾付近に置いたのは、ブラウザが HTML をファイルに現れる順番で読み込むからです。もし JavaScript が最初に読み込まれ、その下の HTML に影響を与えると見られる場合、 HTML の準備ができる前に JavaScript が読み込まれ、正しく動作できない場合があります。したがって、 HTML ページの末尾付近に JavaScript を配置することは多くの場合、最良の方法です。

+

: 上記の説明で {{htmlelement("script")}} 要素を HTML ファイルの末尾付近に置いたのは、ブラウザーがファイルに現れる順番でコードを読み込むからです

+ +

JavaScript が先に読み込まれ、まだ読み込まれていない HTML に影響を与えることになると、問題が生じる可能性があります。 JavaScript を HTML ページの下部に配置することは、この依存関係に対応する一つの方法です。その他の方法については、スクリプトの読み込み戦略をご覧ください。

-

何が起きたか

+

何が起きたのか

-

JavaScript を使用して、見出しの文字列が "Hello world!" に変更されました。最初に {{domxref("Document.querySelector", "querySelector()")}} と呼ばれる関数を使用して見出しの参照を取得し、 myHeading と呼ばれる変数に格納しています。これは CSS のセレクターを使用するのととてもよく似ています。要素に対して何かをしたくなったら、まずその要素を選択する必要があります。

+

JavaScript を使用して、見出しの文字列が Hello world! に変更されました。最初に {{domxref("Document.querySelector", "querySelector()")}} と呼ばれる関数を使用して見出しの参照を取得し、 myHeading と呼ばれる変数に格納しています。これは CSS のセレクターを使用するのととてもよく似ています。要素に対して何かをしたくなったら、まずその要素を選択する必要があります。

-

その後、myHeading 変数の {{domxref("Node.textContent", "textContent")}} プロパティ(見出しの内容を表す)の値を "Hello world!" に設定します。

+

その後、myHeading 変数の {{domxref("Node.textContent", "textContent")}} プロパティ (見出しの内容を表す) の値を Hello world! に設定します。

-

: 上の例で使用した機能はどちらもドキュメントオブジェクトモデル (DOM) API の一部であり、これを使って文書を操作することができます。

+

: 上の例で使用した機能はどちらもドキュメントオブジェクトモデル (DOM) API の一部であり、これを使って文書を操作することができます。

-

言語の短期集中コース

+

言語の短期集中コース

どのように動作するかをよりよく理解できるように、 JavaScript 言語の基本機能のいくつかを説明しましょう。これらの機能はすべてのプログラミング言語に共通しているので、これらの基本をマスターすれば、ほとんど何でもプログラムできるようになります!

-

重要: この記事では、 JavaScript コンソールにサンプルコードを入力して、何が起こるのかを確認してみます。 JavaScript コンソールの詳細については、 ブラウザ開発ツールを探るを参照してください。

+

重要: この記事では、 JavaScript コンソールにサンプルコードを入力して、何が起こるのかを確認してみます。 JavaScript コンソールの詳細については、 ブラウザー開発ツールを探るを参照してください。

-

変数

+

変数

-

{{Glossary("Variable", "変数")}} は、値を格納できる入れ物です。まず、 var (説明はややこしいですが、推奨しません) または let というキーワードと、その後に任意の名前を指定することで、変数を宣言します。

+

{{Glossary("Variable", "変数")}} は、値を格納できる入れ物です。まず、 var (説明はややこしいですが、推奨しません) または let というキーワードと、その後に任意の名前を指定することで、変数を宣言します。

-
let myVariable;
+
let myVariable;
-

: 行末のセミコロンは文が終わる場所を示します。単一の行で複数の文を区切る場合には絶対に必要です。しかし、個々の文の末尾に置くことが良い習慣だと信じている人もいます。使用する場面と使用しない場合については他のルールもあります。詳しくは Your Guide to Semicolons in JavaScript を参照してください。

+

: 行末のセミコロンは文が終わる場所を示します。単一の行で複数の文を区切る場合には絶対に必要です。しかし、個々の文の末尾に置くことが良い習慣だと信じている人もいます。使用する場面と使用しない場合については他のルールもあります。詳しくは Your Guide to Semicolons in JavaScript を参照してください。

-

: 変数にはほとんど何でも名前を付けることができますが、いくらかの制約があります(変数の命名規則についてはこの記事を参照してください)。自信がない場合は、有効かどうか変数名を調べることができます。

+

: 変数にはほとんど何でも名前を付けることができますが、いくらかの制約があります(変数の命名規則についてはこの記事を参照してください)。自信がない場合は、有効かどうか変数名を調べることができます。

@@ -100,24 +102,25 @@ myHeading.textContent = 'Hello world!';
-

: varlet のより詳しい違いは、var と let の違いを見てください。

+

: varlet のより詳しい違いは、var と let の違いを見てください。

変数を宣言したら、以下のように値を割り当てることができます。

-
myVariable = 'Bob';
+
myVariable = 'Bob';
+

好みに応じて、両方の操作を同一の行で行うことができます。

-
let myVariable = 'Bob';
+
let myVariable = 'Bob';

変数の値は、名前で呼び出すだけで取得することができます。

-
myVariable;
+
myVariable;

変数に値を代入した後で、変更することもできます。

-
let myVariable = 'Bob';
+
let myVariable = 'Bob';
 myVariable = 'Steve';

なお、変数は様々なデータ型の値を保持することもできます。

@@ -143,7 +146,7 @@ myVariable = 'Steve';
{{Glossary("Boolean")}} - 真偽値。 truefalse は JS では特別なキーワードであり、引用符は必要ない。 + 論理値。 truefalse は JS では特別なキーワードであり、引用符は必要ありません。 let myVariable = true; @@ -164,20 +167,20 @@ myVariable = 'Steve';

ではなぜ変数が必要なのでしょうか。何か面白いプログラミングをするには変数が必要です。値が変更できなければ、挨拶のメッセージをパーソナライズしたり、画像ギャラリーに表示されている画像を変更するなどの動的な操作ができないのです。

-

コメント

+

コメント

コメントは、ブラウザーから無視される、コードの間に入れられた短いテキストスニペットです。CSS と同じように、JavaScript のコードではコメントを付けることができます。

-
/*
+
/*
 挟まれているすべてがコメントです。
 */

コメントに改行が含まれていない場合、次のように 2 つのスラッシュの後ろに記載する方が簡単です :

-
// これはコメントです
+
// これはコメントです
 
-

演算子

+

演算子

{{Glossary("operator", "演算子")}}は、2 つの値 (または変数) に基づいて結果を生成する数学的な記号です。次の表では、JavaScript コンソールで試してみるいくつかの例とともに、最も単純な演算子をいくつか見ることができます。

@@ -192,7 +195,7 @@ myVariable = 'Steve';
- 追加/連結 + 加算/連結 2 つの数字を加えるか、2 つの文字列を結合します。 + 6 + 9;
@@ -214,7 +217,7 @@ myVariable = 'Steve';
等価 - 2 つの値と型が互いに等しいかどうかを調べ、true / false (真偽値)の結果を返します。 + 2 つの値と型が互いに等しいかどうかを調べ、true/false (論理値)の結果を返します。 === let myVariable = 3;
myVariable === 4;
@@ -229,9 +232,9 @@ myVariable = 'Steve';

let myVariable = 3;
!(myVariable === 3);

-

「等しくない」は、基本的に同じ結果を異なる構文で与えます。ここでは「myVariable が 3 とは等しくない」ことをテストします。 myVariable は 3 と等しいので、false を返します。

+

「等しくない」は、基本的に同じ結果を異なる構文で与えます。ここでは「myVariable が 3 とは等しくない」ことをテストします。 myVariable は 3 と等しいので、false を返します。

-

let myVariable = 3;
+

let myVariable = 3;
myVariable !== 3;

@@ -244,194 +247,203 @@ myVariable = 'Steve';

: データ型を混在させると、計算を実行するときに奇妙な結果になる可能性があるため、変数を正しく参照し、期待通りの結果を得るように注意してください。例えばコンソールに '35' + '25' と入力してみてください。期待通りの結果にならないのはなぜでしょうか。引用符は数字を文字列に変換するので、数字を加算するのではなく、文字列を連結する結果になったのです。 35 + 25 を入力すれば、正しい結果が得られます。

-

条件文

+

条件文

条件文は、ある式が true を返すかどうかをテストし、その結果次第でそれぞれのコードを実行するコード構造です。条件文のよくある形は if ... else 文です。例えば以下の通りです。

-
let iceCream = 'チョコレート';
+
let iceCream = 'チョコレート';
 if(iceCream === 'チョコレート') {
   alert('やった、チョコレートアイス大好き!');
 } else {
   alert('あれれ、でもチョコレートは私のお気に入り......');
 }
-

if( ... ) の中の式が条件です — ここでは等価演算子を使用して、変数 iceCreamチョコレートという文字列とをを比較し、2 つが等しいかどうかを調べています。この比較が true を返した場合、コードの最初のブロックが実行されます。比較が真でない場合、最初のブロックはスキップされ、else 文の後にある 2番目のコードブロックが代わりに実行されます。

+

if( ... ) の中の式が条件です — ここでは等価演算子を使用して、変数 iceCreamチョコレートという文字列とをを比較し、2 つが等しいかどうかを調べています。この比較が true を返した場合、コードの最初のブロックが実行されます。比較が真でない場合、最初のブロックはスキップされ、 else 文の後にある 2番目のコードブロックが代わりに実行されます。

-

関数

+

関数

{{Glossary("Function", "関数")}} は、再利用したい機能をパッケージ化する方法です。プロシージャが必要なときは、毎回コード全体を書くのではなく関数名を使って関数を呼び出すことができます。すでにいくつかの関数の仕様を見てきました。例えば以下のようなものです。

  1. -
    let myVariable = document.querySelector('h1');
    +
    let myVariable = document.querySelector('h1');
  2. -
    alert('hello!');
    +
    alert('hello!');
-

これらの関数、document.querySelectoralert は、必要なときにいつでも使えるようブラウザに組み込まれています。

+

これらの関数、 document.querySelectoralert は、必要なときにいつでも使えるようブラウザーに組み込まれています。

もし変数名に見えるものがあったとしても、その後に括弧 () が付いていれば、おそらくそれは関数です。関数は普通、仕事をするのに必要な小さなデータである{{Glossary("Argument", "引数")}}を取ります。引数は括弧の中に入れ、複数の引数がある場合はカンマで区切ります。

-

例えば、alert() 関数はブラウザのウィンドウにポップアップボックスを表示しますが、ポップアップボックスに何を書き込むかを関数に指示するために、文字列を引数として渡す必要があります。

+

例えば、 alert() 関数はブラウザーのウィンドウにポップアップボックスを表示しますが、ポップアップボックスに何を書き込むかを関数に指示するために、文字列を引数として渡す必要があります。

嬉しいことに、自分で関数を定義することができます。次の例では、引数として 2 つの数値をとり、それらを乗算するという単純な関数を記載します。

-
function multiply(num1,num2) {
+
function multiply(num1,num2) {
   let result = num1 * num2;
   return result;
 }
-

上記の関数をコンソールで実行し、いくつかの引数を指定してテストしてみてください。例えば次のようなものです :

+

上記の関数をコンソールで実行し、いくつかの引数を指定してテストしてみてください。例えば次のようなものです。

-
multiply(4,7);
-multiply(20,20);
-multiply(0.5,3);
+
multiply(4, 7);
+multiply(20, 20);
+multiply(0.5, 3);
-

: return 文は result の値を関数内から関数の外に戻すことをブラウザに指示し、それを利用できるようにします。これが必要な理由は、関数内で定義された変数が、その関数内でしか利用できないためです。これは変数の{{Glossary("Scope", "スコープ")}}と呼ばれています(変数のスコープのより詳しい説明をお読みください)。

+

: return 文は result の値を関数内から関数の外に戻すことをブラウザーに指示し、それを利用できるようにします。これが必要な理由は、関数内で定義された変数が、その関数内でしか利用できないためです。これは変数の{{Glossary("Scope", "スコープ")}}と呼ばれています(変数のスコープのより詳しい説明をお読みください)。

-

イベント

+

イベント

-

Web サイトを実際にインタラクティブにするには、イベントが必要です。イベントは、ブラウザの中で起きていることを検出し、その応答としてコードを実行するコード構造です。最も分かりやすい例は click イベントで、マウスで何かをクリックするとブラウザによって発火されるものです。これを実行するには、コンソールに以下のように入力してから、現在の Web ページ上をクリックしてください。

+

ウェブサイトを実際にインタラクティブにするには、イベントが必要です。イベントは、ブラウザーの中で起きていることを検出し、その応答としてコードを実行するコード構造です。最も分かりやすい例は click イベントで、マウスで何かをクリックするとブラウザーによって発行されるものです。これを実行するには、コンソールに以下のように入力してから、現在のウェブページ上をクリックしてください。

-
document.querySelector('html').onclick = function() {
+
document.querySelector('html').onclick = function() {
     alert('痛っ! つつくのはやめて!');
 }
-

要素にイベントを割り当てる方法はたくさんあります。ここでは {{htmlelement("html")}} 要素を選択し、onclick ハンドラのプロパティに、クリックイベントで実行したいコードを含む匿名 (つまり名前がない) 関数を代入します。

+

要素にイベントを割り当てる方法はたくさんあります。ここでは {{htmlelement("html")}} 要素を選択し、onclick ハンドラープロパティに、クリックイベントで実行したいコードを含む無名 (つまり名前がない) 関数を代入します。

なお、

-
document.querySelector('html').onclick = function() {};
+
document.querySelector('html').onclick = function() {};

は以下のものと同等です。

-
let myHTML = document.querySelector('html');
+
let myHTML = document.querySelector('html');
 myHTML.onclick = function() {};

短くしただけです。

-

Web サイトの例を膨らませる

+

ウェブサイトの例を膨らませる

+ +

さて、 JavaScript の基本のおさらいが終わったところで、例題のサイトに新しい機能を追加してみましょう。

-

ここまで JavaScript の基本を少し見てきましたが、何ができるのかを見るために、例のサイトにいくつかクールな機能を追加してみましょう。

+

先に進む前に、 main.js ファイルの現在の内容を削除して、空のファイルを保存してください。そうしないと、 "Hello world!" の例で使用した既存のコードが、これから追加する新しいコードと衝突してしまいます。

-

画像の切り替えの追加

+

画像の切り替えの追加

このセクションでは、 DOM API 機能をもっと使用して、サイトに画像を追加しましょう。画像をクリックすると JavaScript を使用して 2 つの画像を切り替えることができます。

  1. まずサイトに掲載したいと思う別な画像を見つけてください。最初の画像と同じサイズか、できるだけ近いものを使用してください。
  2. -
  3. この画像を images フォルダに保存してください。
  4. -
  5. この画像の名前を 'firefox2.png' (引用符なし) に変更してください。
  6. -
  7. main.js ファイルに移動し、次の JavaScript を入力します。(もし "hello world" の JavaScript がまだ残っている場合は、削除してください。) -
    let myImage = document.querySelector('img');
    + 
  8. この画像を images フォルダーに保存してください。
  9. +
  10. この画像の名前を firefox2.png に変更してください。
  11. +
  12. main.js ファイルに次の JavaScript を入力してください。 +
    let myImage = document.querySelector('img');
     
     myImage.onclick = function() {
         let mySrc = myImage.getAttribute('src');
         if(mySrc === 'images/firefox-icon.png') {
    -      myImage.setAttribute ('src','images/firefox2.png');
    +      myImage.setAttribute('src','images/firefox2.png');
         } else {
    -      myImage.setAttribute ('src','images/firefox-icon.png');
    +      myImage.setAttribute('src','images/firefox-icon.png');
         }
     }
  13. -
  14. index.html をブラウザに読み込みます。画像をクリックすると、もう一方の画像に変わります。
  15. +
  16. index.html をブラウザーに読み込みます。画像をクリックすると、もう一方の画像に変わります。
-

{{htmlelement("img")}} 要素への参照を変数 myImage に格納します。次にこの変数の onclick イベントハンドラプロパティに、名前のない関数(無名関数)を代入します。そうすれば、この要素がクリックされるたびに以下の動きをします。

+

{{htmlelement("img")}} 要素への参照を変数 myImage に格納します。次にこの変数の onclick イベントハンドラープロパティに、名前のない関数(無名関数)を代入します。そうすれば、この要素がクリックされるたびに以下の動きをします。

  1. 画像の src 属性の値を取得します。
  2. 条件文を使って、src の値が元の画像のパスと等しいかどうかをチェックします。
      -
    1. そうであれば、src の値を 2番目の画像へのパスに変更し、もう一方の画像が強制的に {{htmlelement("img")}} 要素の中に読み込まれるようにします。
    2. -
    3. そうでない(すでに変更されている)場合、src の値を元の画像のパスに戻して、元の状態に戻ります。
    4. +
    5. そうであれば、src の値を 2 番目の画像へのパスに変更し、もう一方の画像が強制的に {{htmlelement("img")}} 要素の中に読み込まれるようにします。
    6. +
    7. そうでない (すでに変更されている) 場合、src の値を元の画像のパスに戻して、元の状態に戻ります。
-

パーソナライズされた挨拶メッセージの追加

+

パーソナライズされた挨拶メッセージの追加

-

次に、もう 1 つの小さなコードを追加し、ユーザがサイトにアクセスしたときに、ページの表題をパーソナライズされた挨拶メッセージに変更してみましょう。この挨拶メッセージは、ユーザがサイトを離れて後で戻った時にも保存されるようにします。Web Storage API を使用して保存しましょう。したがって、必要な時にいつでもユーザと挨拶メッセージを変更できるオプションも用意しましょう。

+

次に、もう 1 つの小さなコードを追加し、ユーザーがサイトにアクセスしたときに、ページの表題をパーソナライズされた挨拶メッセージに変更してみましょう。この挨拶メッセージは、ユーザーがサイトを離れて後で戻った時にも保存されるようにします。Web Storage API を使用して保存しましょう。したがって、必要な時にいつでもユーザーと挨拶メッセージを変更できるオプションも用意しましょう。

    -
  1. index.html では、 {{htmlelement("script")}} 要素の直前に次の行を追加します : +
  2. index.html では、 {{htmlelement("script")}} 要素の直前に次の行を追加します。 -
    <button>ユーザを変更</button>
    +
    <button>ユーザーを変更</button>
  3. main.js では、次のコードを下記のとおりにファイルの最後に配置します。これは新しいボタンと見出しへの参照を変数に格納します。 -
    let myButton = document.querySelector('button');
    +  
    let myButton = document.querySelector('button');
     let myHeading = document.querySelector('h1');
  4. パーソナライズされた挨拶を設定する以下の関数を追加しましょう。まだ何も起こりませんが、すぐに修正します。 -
    function setUserName() {
    +  
    function setUserName() {
       let myName = prompt('あなたの名前を入力してください。');
       localStorage.setItem('name', myName);
       myHeading.textContent = 'Mozilla はすばらしいよ、' + myName;
     }
    - この関数では prompt() 関数を使用して、alert() のようにダイアログボックスを表示しています。しかし、prompt() はユーザにデータを入力するよう求め、ユーザが OK を押した後に変数にそのデータを格納します。この場合、ユーザに名前を入力するよう求めます。次に、localStorage と呼ばれる API を呼び出すことで、ブラウザにデータを格納して後で受け取ることができます。localStorage の setItem() 関数を使って、'name' と呼ばれるデータを作成し、myName に入っているユーザから入力されたデータを格納します。最後に、見出しの textContent に文字列と新しく格納されたユーザの名前を設定します。
  5. + この関数では prompt() 関数を使用して、alert() のようにダイアログボックスを表示しています。しかし、prompt()alert() とは異なり、ユーザーにデータを入力するよう求め、ユーザーが OK を押した後に変数にそのデータを格納します。この場合、ユーザーに名前を入力するよう求めます。次に、localStorage と呼ばれる API を呼び出すことで、ブラウザーにデータを格納して後で受け取ることができます。 localStorage の setItem() 関数を使って、'name' と呼ばれるデータを作成し、 myName に入っているユーザーから入力されたデータを格納します。最後に、見出しの textContent に文字列と新しく格納されたユーザーの名前を設定します。
  6. 次に、この if ... else ブロックを追加します。これは初期化コードと呼ぶことができ、最初の読み込みでアプリを構成します。 -
    if(!localStorage.getItem('name')) {
    +  
    if(!localStorage.getItem('name')) {
       setUserName();
     } else {
       let storedName = localStorage.getItem('name');
       myHeading.textContent = 'Mozilla はすばらしいよ、' + storedName;
     }
    - このブロックでは、最初に name のデータが存在しているかどうかをチェックするために否定演算子(! で表される論理否定)を使用しています。存在しない場合は、作成するために setUserName() 関数が実行されます。存在する場合は(つまり、以前の訪問時にユーザが設定した場合)、 getItem() を使用して格納された名前を受け取り、 setUserName() の中で行ったのと同様に、見出しの textContent に文字列とユーザの名前を設定します。
  7. -
  8. 最後に、以下の onclick イベントハンドラをボタンに設定します。クリックすると、setUserName() 関数が実行されます。これでユーザがボタンを押すことで、好きな時に新しい名前を設定できるようになります。 -
    myButton.onclick = function() {
    +  このブロックでは、最初に name のデータが存在しているかどうかをチェックするために否定演算子 (! で表される論理否定) を使用しています。存在しない場合は、作成するために setUserName() 関数が実行されます。存在する場合は (つまり、以前の訪問時にユーザーが設定した場合)、 getItem() を使用して格納された名前を受け取り、 setUserName() の中で行ったのと同様に、見出しの textContent に文字列とユーザーの名前を設定します。
  9. +
  10. 最後に、以下の onclick イベントハンドラーをボタンに設定します。クリックすると、setUserName() 関数が実行されます。これでユーザーがボタンを押すことで、好きな時に新しい名前を設定できるようになります。 +
    myButton.onclick = function() {
       setUserName();
     }
     
-

サイトにアクセスしてみると、ページがユーザ名を尋ね、パーソナライズされたメッセージを表示します。好きなときにボタンを押すと名前を変えることができます。おまけに、名前は localStorage 内に格納されているため、サイトを閉じた後も名前が保持され、次にサイトを開いたときにパーソナライズされたメッセージが保持されます。

-

A user name of null?

-

この例を実行してユーザー名を入力するダイアログボックスが出たとき、キャンセルボタンを押してみてください。結果として"Mozilla is cool, null"というタイトルが表示されるでしょう。これはプロンプトをキャンセルしたときに、値が null、つまり値がないことに言及する JavaScript の特殊な値にセットされているためです。

+

この例を実行してユーザー名を入力するダイアログボックスが出たとき、キャンセルボタンを押してみてください。結果として "Mozilla is cool, null" というタイトルが表示されるでしょう。これはプロンプトをキャンセルしたときに、値が null、つまり値がないことを示す JavaScript の特殊な値に設定されるためです。

-

また何も入れずに OK を押してみてください — 結果として"Mozilla is cool,"というタイトルが表示され、これは理由が明白です。

+

また何も入れずに OK を押してみてください — 結果として "Mozilla is cool," というタイトルが表示され、これは理由が明白です。

-

この問題を避けるには、ユーザーが null や空白の名前を入力していないかチェックするよう、setUserName() 関数を書き換えます:

+

この問題を避けるには、ユーザーーが null や空白の名前を入力していないかチェックするよう、setUserName() 関数を書き換えます。

-
function setUserName() {
+
function setUserName() {
   let myName = prompt('Please enter your name.');
-  if(!myName || myName === null) {
+  if(!myName) {
     setUserName();
   } else {
     localStorage.setItem('name', myName);
-    myHeading.innerHTML = 'Mozilla is cool, ' + myName;
+    myHeading.textContent = 'Mozilla is cool, ' + myName;
   }
 }

人間の言語では — myName に値がない場合や、nullの場合、 最初から setUserName() を実行します。値がない場合 (上記の式が真でない場合)には、localStorage に値をセットして、見出しのテキストにもセットします。

-

まとめ

+

まとめ

最後までこの記事の手順に従った場合は、最終的に次のようなページが表示されているでしょう (こちらで作成した版を表示することもできます)。

-

+

行き詰まったら、自分の作業を Github 上の完成したサンプルコードと比べてみてください。

私たちは JavaScript に少し触れただけです。楽しく遊んだり、もっと上達したい場合は、JavaScript の学習トピックに進んでください。

+

関連情報

+ +
+
JavaScript による動的なクライアント側スクリプト
+
もっと詳細な JavaScript に飛び込みましょう。
+
Learn JavaScript
+
ウェブ開発者を目指す方に最適な教材です! インタラクティブな環境で、短いレッスンとインタラクティブなテスト、自動評価によるガイドで、 JavaScript を学ぶことができます。最初の 40 レッスンは無料です。全コースは少額の一括払いでご利用いただけます。
+
+

{{PreviousMenuNext("Learn/Getting_started_with_the_web/CSS_basics", "Learn/Getting_started_with_the_web/Publishing_your_website", "Learn/Getting_started_with_the_web")}}

-

このモジュール

+

このモジュール

diff --git a/files/ja/web/html/element/hgroup/index.html b/files/ja/web/html/element/hgroup/index.html index 50fb215618..ac206a5871 100644 --- a/files/ja/web/html/element/hgroup/index.html +++ b/files/ja/web/html/element/hgroup/index.html @@ -9,25 +9,18 @@ tags: - HTML5 - Reference - Web -browser-compat: html.elements.hgroup translation_of: Web/HTML/Element/hgroup --- -
{{HTMLRef}}
+
{{HTMLRef}}{{deprecated_header}}
-
-

Warning

-

<hgroup> は使用すべきではありません。どの支援技術も対応しておらず、その結果、その中に配置された見出しの支援に悪影響を及ぼすためです。

-

詳細については、以下の使用上の注意を参照してください。

-
- -

<hgroup>HTML の要素で、文書のセクションの、複数レベルの見出しを表します。これは <h1>–<h6> 要素のセットをグループ化します。

+

HTML の <hgroup> 要素は、文書のセクションの、複数レベルの見出しを表します。これは <h1>–<h6> 要素のセットをグループ化します。

{{EmbedInteractiveExample("pages/tabbed/hgroup.html", "tabbed-standard")}}
- + @@ -65,7 +58,7 @@ translation_of: Web/HTML/Element/hgroup

<hgroup> 要素は HTML5 (W3C) 仕様から削除されましたが、 WHATWG 版の HTML には依然として含まれています。ほとんどのブラウザーで部分的に実装されており、実装が削除される可能性は低くなっています。
- ただし、<hgroup> 要素の主要な目的は HTML 仕様書で定義されたアウトラインのアルゴリズムによって見出しをどのように表示するかに作用することですが、どのブラウザーでもアウトラインのアルゴリズムは実装されていないため<hgroup> のセマンティクスは実際のところ、理論上のものになっています。
+ ただし、<hgroup> 要素の主要な目的は HTML 仕様書で定義されたアウトラインのアルゴリズムによって見出しをどのように表示するかに作用することですが、どのブラウザーでもアウトラインのアルゴリズムは実装されていないため<hgroup> のセマンティクスは実際のところ、理論上のものになっています。
HTML5 (W3C) 仕様書では、<hgroup>を使用せずに副見出し、サブタイトル、代替タイトル、スローガンをマークアップする方法についてアドバイスを提供しています。

@@ -73,7 +66,7 @@ translation_of: Web/HTML/Element/hgroup

言い換えると、 <hgroup> 要素は副次的な子の <h1>–<h6> がアウトライン内で独自のセクションを生成することを妨げます。これらの <h1>–<h6> 要素は <hgroup> の子でなければ通常どおりです。

-

よって HTML 仕様書で定義されているアウトラインのアルゴリズムで生成される理論的なアウトラインでは、<hgroup> は全体としてひとつの論理的な見出しを構成します。そして <hgroup> の子である <h1>–<h6> とともに、理論的なアウトライン内でひとつの論理的な見出しを構成するために複数レベルのユニットとしてのアウトラインになります。

+

よって HTML 仕様書で定義されているアウトラインのアルゴリズムで生成される理論的なアウトラインでは、<hgroup> は全体としてひとつの論理的な見出しを構成します。そして <hgroup> の子である <h1>–<h6> とともに、理論的なアウトライン内でひとつの論理的な見出しを構成するために複数レベルのユニットとしてのアウトラインになります。

このようなアウトラインの (理論的ではない) 描画ビューを生成するために、マルチレベルの性質を伝えるため <hgroup> の見出しをどのように描画するかについて、レンダリングツールのデザインでいくつかの選択が必要です。例えば以下のように、描画されたアウトラインで <hgroup> を表示するさまざまな方法が考えられます:

@@ -118,21 +111,36 @@ translation_of: Web/HTML/Element/hgroup </hgroup> -

アクセシビリティの考慮

+

仕様書

-

hgroup が存在すると、見出しグループの副見出しの部分に関して支援技術に報告される情報が削除される可能性があります。

+
コンテンツカテゴリーコンテンツカテゴリ フローコンテンツ, 見出しコンテンツ, 知覚可能コンテンツ
+ + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', 'semantics.html#the-hgroup-element', '<hgroup>')}}{{Spec2('HTML WHATWG')}}
-

仕様書

+

アクセシビリティの考慮

-

{{Specifications}}

+

hgroup が存在すると、見出しグループの小見出し部分について支援技術に報告された情報を削除する可能性があります。

ブラウザーの互換性

-

{{Compat}}

+

{{Compat("html.elements.hgroup")}}

関連情報

diff --git a/files/ja/web/javascript/reference/global_objects/date/index.html b/files/ja/web/javascript/reference/global_objects/date/index.html index 88a7ea7880..a5e00b4f68 100644 --- a/files/ja/web/javascript/reference/global_objects/date/index.html +++ b/files/ja/web/javascript/reference/global_objects/date/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Date ---
{{JSRef}}
-

JavaScript の Date オブジェクトは、単一の瞬間の時刻をプラットフォームに依存しない形式で表します。 Date オブジェクトは協定世界時 (UTC) の1970年1月1日からの経過ミリ秒数を表現する Number の値を含んでいます。

+

JavaScript の Date オブジェクトは、単一の瞬間の時刻をプラットフォームに依存しない形式で表します。 Date オブジェクトは協定世界時 (UTC) の1970年1月1日からの経過ミリ秒数を表現する Number 含んでいます。

解説

-- cgit v1.2.3-54-g00ecf