Internet-technologies-javascript

提供:Dev Guides
移動先:案内検索

JavaScript

前書き

*JavaScript* は、オブジェクト指向機能を備えた軽量のインタープリター型プログラミング言語であり、静的HTMLページにインタラクティブ機能を組み込むことができます。

'_JavaScriptコードはコンパイルされませんが、翻訳者によって翻訳されます。 このトランスレータはブラウザに埋め込まれ、javascriptコードの翻訳を担当します。_

キーポイント

  • これは、軽量のインタープリター型プログラミング言語です。
  • ネットワーク中心のアプリケーションを作成するために設計されています。
  • Javaを補完し、Javaと統合されています。
  • HTMLを補完し、HTMLと統合されています *オープンでクロスプラットフォームです

JavaScriptステートメント

JavaScriptステートメントは、実行するアクションをブラウザーに指示するコマンドです。 ステートメントはセミコロン(;)で区切られます。

'_JavaScriptステートメントは、ブラウザーによって行ごとに翻訳されるJavaScriptコードを構成します。_

JavaScriptステートメントの例:

document.getElementById("demo").innerHTML = "Welcome";

次の表は、さまざまなJavaScriptステートメントを示しています-

Sr.No. Statement Description
1. switch case A block of statements in which execution of code depends upon different cases. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a* default *condition will be used.
2. If else The* if* statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
3. While The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.
4. do while Block of statements that are executed at least once and continues to be executed while condition is true.
5. for Same as while but initialization, condition and increment/decrement is done in the same line.
6. for in This loop is used to loop through an object’s properties.
7. continue The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block.
8. break The break statement is used to exit a loop early, breaking out of the enclosing curly braces.
9. function A function is a group of reusable code which can be called anywhere in your programme. The keyword function is used to declare a function.
10. return Return statement is used to return a value from a function.
11. var Used to declare a variable.
12. try A block of statements on which error handling is implemented.
13. catch A block of statements that are executed when an error occur.
14. throw Used to throw an error.

JavaScriptコメント

JavaScriptはCスタイルとC ++スタイルの両方のコメントをサポートします。したがって、

//と行末の間のテキストはコメントとして扱われ、JavaScriptによって無視されます。 *文字/ と*/の間のテキストはコメントとして扱われます。 これは複数行にわたる場合があります。 * JavaScriptは、HTMLコメント開始シーケンス<!-も認識します。 JavaScriptは//コメントと同様に、これを1行のコメントとして扱います。-→ * HTMLコメントの終了シーケンス→はJavaScriptによって認識されないため、//→と記述する必要があります。

<script language="javascript" type="text/javascript">
   <!--

     //this is a comment. It is similar to comments in C++

     /*
 *This is a multiline comment in JavaScript
        * It is very similar to comments in C Programming
      */
  //-->
<script>

JavaScript変数

変数は、情報を保存するための名前付きコンテナと呼ばれます。 これらのコンテナにデータを配置し、コンテナに名前を付けるだけでデータを参照できます。

JavaScriptで変数を宣言するルール

JavaScriptで変数を宣言する際に従うべき重要なルールを以下に示します。

  • JavaScriptでは、変数名は大文字と小文字が区別されます。 aはAとは異なります。
  • 変数名は、アンダースコア(_)または文字(aからzまたはAからZ)、またはドル($)記号でのみ開始できます。
  • 数字(0〜9)は、文字の後にのみ使用できます。
  • 変数名には他の特殊文字は使用できません。

JavaScriptプログラムで変数を使用する前に、宣言する必要があります。 変数は、次のようにvarキーワードで宣言されます-

<script type="text/javascript">
   <!--
      var money;
      var name, age;
  //-->
</script>

変数は、次のように宣言時または宣言後に初期化できます-

<script type="text/javascript">
   <!--
      var name = "Ali";
      var money;
      money = 2000.50;
  //-->
</script>

JavaScriptデータ型

以下に示すように、2種類のデータタイプがあります-

  • プリミティブデータ型
  • 非プリミティブデータ型

次の表は、javaScriptで使用できる Primitive Data Types について説明しています

Sr.No. Datatype Description
1.

String

文字のグループを単一の値として含めることができます。 二重引用符で表されます。 var x =“チュートリアル”。

2.

Numbers

小数ありまたはなしの数値が含まれます。 E.g. var x = 44、y = 44.56;

3.

Booleans

trueまたはfalseの2つの値のみが含まれます。 E.g. var x = true、y = false。

4.

Undefined

値のない変数は、未定義と呼ばれます。 E.g. var x;

5.

Null

変数にnullを割り当てると、空になります。 E.g. var x = null;

次の表は、javaScriptの*非プリミティブデータ型*について説明しています

Sr.No. Datatype Description
1. ArrayCan contain groups of values of same type. E.g. var x=\{1,2,3,55};
2. ObjectsObjects are stored in property and value pair. E.g. var rectangle = \{ length: 5, breadth: 3};

JavaScript関数

関数は、プログラム内の任意の場所で呼び出すことができる再利用可能なステートメント(コード)のグループです。 javascriptでは、キーワードを使用して関数を宣言または定義します。

キーポイント

  • 関数を定義するには、functionキーワード、続いてfunctionname、その後に括弧()を使用します。
  • 括弧内に、パラメーターまたは属性を定義します。
  • reusabeステートメントのグループ(コード)は、中括弧\ {}で囲まれています。 このコードは、関数が呼び出されるたびに実行されます。

構文

function functionname (p1, p2) {
   function coding…
}

JavaScriptオペレーター

演算子は、1つ、2つ、またはそれ以上のオペランドに対して操作を実行するために使用されます。 演算子は、+、=、*、%などの記号で表されます。 以下は、JavaScriptでサポートされている演算子です-

  • 算術演算子
  • 比較演算子
  • 論理(またはリレーショナル)演算子
  • 割り当て演算子
  • 条件付き(または3項)演算子
  • 算術演算子

算術演算子

次の表は、javascriptでサポートされているすべての算術演算子を示しています-

Operator Description Example
+ Add two operands. 10 + 10 will give 20
- Subtract second operand from the first. 10 – 10 will give 0
* Multiply two operands. 10* 30 will give 300
/ Divide numerator by denominator 10/10 will give 1
% It is called modulus operator and gives remainder of the division. 10 % 10 will give 0
++ Increment operator, increases integer value by one 10 ++ will give 11
 —  Decrement operator, decreases integer value by one 10 – will give 9

比較演算子

次の表は、javascriptでサポートされているすべての比較演算子を示しています-

Operator Description Example
== Checks if values of two operands are equal or not, If yes then condition becomes true. 10 == 10 will give true
!= Not Equal to operatorChecks if the value of two operands is equal or not, if values are not equal then condition becomes true. 10 !=10 will give false
> Greater Than operatorChecks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. 20 > 10 will give true
< Less than operator Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. 10 < 20 will give true
>= Greater than or equal to operatorChecks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. 10 >=20 will give false
Less than or equal to operatorChecks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. 10 ⇐20 will give true.

論理演算子

次の表は、javascriptでサポートされているすべての論理演算子を示しています-

Operator Description Example
&& Logical *AND *operator returns true if both operands are non zero. 10 && 10 will give true.
Logical* OR *operator returns true If any of the operand is non zero 10
0 will give true. ! Logical* NOT* operator complements the logical state of its operand.

割り当て演算子

次の表は、javascriptでサポートされているすべての割り当て演算子を示しています-

Operator Description Example
= Simple Assignment operatorAssigns values from right side operands to left side operand. C = A + B will assign value of A + B into C
+= Add AND assignment operatorIt adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operatorIt subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operatorIt multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operatorIt divides left operand with the right operand and assign the result to left operand C/= A is equivalent to C = C/A
%= Modulus AND assignment operatorModulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

条件演算子

3つのオペランドがあるため、三項演算子とも呼ばれます。

Operator Description Example
?: Conditional Expression If Condition is true? Then value X : Otherwise value Y

制御構造

制御構造は、実際にプログラムの実行の流れを制御します。 以下は、javascriptでサポートされているいくつかの制御構造です。

  • if…else
  • スイッチケース
  • whileループ
  • whileループ
  • forループ

もし…他

ifステートメントは、JavaScriptが決定を下し、ステートメントを条件付きで実行できるようにする基本的な制御ステートメントです。

構文

if (expression){
   Statement(s) to be executed if expression is true
}

<script type="text/javascript">
   <!--
      var age = 20;
      if( age > 18 ){
         document.write("<b>Qualifies for driving</b>");
      }
  //-->
</script>

スイッチケース

switchステートメントの基本的な構文は、評価する式と、式の値に基づいて実行するいくつかの異なるステートメントを指定することです。 インタープリターは、一致が見つかるまで、式の値に対して各ケースをチェックします。 一致するものがない場合、デフォルトの条件が使用されます。

構文

switch (expression) {
   case condition 1: statement(s)
                    break;
   case condition 2: statement(s)
                    break;
   ...
   case condition n: statement(s)
                    break;
   default: statement(s)
}

<script type="text/javascript">
   <!--
      var grade='A';
      document.write("Entering switch block<br/>");
      switch (grade) {
         case 'A': document.write("Good job<br/>");
            break;
         case 'B': document.write("Pretty good<br/>");
            break;
         case 'C': document.write("Passed<br/>");
            break;
         case 'D': document.write("Not so good<br/>");
            break;
         case 'F': document.write("Failed<br/>");
            break;
         default:  document.write("Unknown grade<br/>")
      }
      document.write("Exiting switch block");
  //-->
</script>

whileループ

do …​ whileループは、ループの最後に条件チェックが発生することを除いて、whileループに似ています。 つまり、条件が偽であっても、ループは常に少なくとも1回は実行されます。

構文

do{
   Statement(s) to be executed;
} while (expression);

<script type="text/javascript">
   <!--
      var count = 0;
      document.write("Starting Loop" + "<br/&gt");
      do{
         document.write("Current Count : " + count + "<br/&gt");
         count++;
      }while (count < 0);
      document.write("Loop stopped!");
  //-->
</script>

これにより、次の結果が生成されます–

Starting Loop
Current Count : 0
Loop stopped!

Whileループ

whileループの目的は、式がtrueである限り、ステートメントまたはコードブロックを繰り返し実行することです。 式がfalseになると、ループは終了します。

構文

while (expression){
   Statement(s) to be executed if expression is true
}

<script type="text/javascript">
   <!--
      var count = 0;
      document.write("Starting Loop" + "<br/>");
      while (count < 10){
         document.write("Current Count : " + count + "<br/>");
         count++;
      }
      document.write("Loop stopped!");
  //-->
</script>

これにより、次の結果が生成されます–

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

ループ用

forループは、ループの最もコンパクトな形式であり、次の3つの重要な部分が含まれています-

  • カウンターを開始値に初期化するループ初期化。 初期化ステートメントは、ループが始まる前に実行されます。
  • 指定された条件が真かどうかをテストするテストステートメント。 条件がtrueの場合、ループ内で指定されたコードが実行され、そうでない場合はループが出力されます。
  • カウンターを増減できる反復ステートメント。

構文

for (initialization; test condition; iteration statement){
   Statement(s) to be executed if test condition is true
}

<script type="text/javascript">
   <!--
      var count;
      document.write("Starting Loop" + "<br/>");
      for(count = 0; count < 10; count++){
         document.write("Current Count : " + count );
         document.write("<br/>");
      }
      document.write("Loop stopped!");
  //-->
</script>

これは、whileループに似ている次の結果を生成します-

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

サンプルプログラムの作成

以下は、ボタンをクリックすると時間を表示するサンプルプログラムです。

<html>
   <body>
      <button onclick="this.innerHTML=Date()">The time is?</button>
      <p>Click to display the date.</p>
      <button onclick="displayDate()">The time is?</button>
      <script>
         function displayDate() {
            document.getElementById("demo").innerHTML = Date();
         }</script>

         <p id="demo"></p>
      </script>
   </body>
</html>

出力

internet_technologies_tutorial