LoginSignup
7
6

More than 5 years have passed since last update.

javascript入門(ドットインストール)

Posted at

概要
-ブラウザに実装されているスクリプト言語
-動きのあるウェブサイト
-javaとは異なる

java script の書き方

<!DOCTYPE html>
<html lang=“ja”>
<head>
     <meta charset=“utf-8”>
     <title></title>
</head>
<body>
     <script src=“myscript.js"></script>
     <script>       
          console.log(“hello world!”);
     </script>
</body>
</html>

コメントの書き方

  /*
      コメント
      コメント
      コメント
*/
     //コメント 

変数

 /* 
               変数 : データにつけるラベル

               データ型
               -文字列
               -数値
               -真偽値(true / false)
               -オブジェクト
                    -配列
                    -関数
                    -組み込みオブジェクト
               - undefined 定義されていない
               -    null 何もない
          */
          var msg;
          msg = “hello world!”;
          var msg = “hello world”;
          console.log(msg)  

数値の使用

 /*
               数値
                    10
                    2.5
                    -2.5
               演算子
                    + - * / %
                    += 代入を伴う演算子
                    ++   -- 単項演算子
          */
          var x;
          x = 10 * 2; //20
          x = 10%3;
          x = x +5;
          x++;
          x--;
          console.log(x);

文字列の使用

var s = “hello”;
var s = ‘hello’;
// \n 改行
// \t タブ

s = ‘it \’ s \n a pe \t n.’;

s = “hello” + “world”;
s = “5” + “5”; // “55”

if文の使用

 条件分岐
if(条件){

}else{

}

比較演算子

<
= <=
=== ==
!== !=

論理演算子
AND &&
OR ||
NOT !
socre > 60 && score <80

var score = 40;
if(score > 60){
     console.log(“ok!”);
else if(score > 40){
     console.log(“soso...")
}
}else{
     console.log(“ng!”);
}

真偽値と三項演算子

真偽値

      文字列:空文字以外だったらtrue
      数値:0かNaN 以外だったらtrue
      true / false
      object: null 以外だったらtrue
      undefined, null -> false

if(x){
//処理
}

if(x !== ‘ ‘){
//処理
}

三項演算子

var a,b,c;
if(条件){
a=b;
} else{
a=c;
}
a= (条件) ? b:c;

var max, x,y;
max =(x >y) ? x : y;

switch文の使用

breakのつけ忘れ注意

var signal =“red”;
switch(signal){
 case”red”:
          console.log(“stop!”);
          break;

 case”green”:
 case”blue”;
          console.log(“go!”);
          break;
 case”yellow”:
          console.log(“slow down!”);
          break; 
default:
     console.log(“wrong signal”)
     break;
}

while文

ループ処理

var i = 0;
while(i < 10){
     console.log(i);
     i++
}

var i = 0;
do {
     console.log(i);
     i++;
     }while(i <10);

for文の使用

for(var i =0; i <10 ; i++){
     console.log(i);
}

break ループ処理を抜ける

for(var i =0; i <10 ; i++){
     if(i ===5){
     break;
     }
     console.log(i);
}

continue ループ処理を一回スキップ

for(var i =0; i <10 ; i++){
     if(i ===5){
     continue;
     }
     console.log(i);
} 

alert,confirm, prompt

//ユーザーに何らかの情報を提示
alert(“hello”);

//OKとキャンセルボタンの提示
var answer = confirm(“are you sure?”);

例)
if(confirm(“本当の削除しますか?”)){
//削除処理
}

//ユーザーから情報を受け取る
var name = prompt(“お名前は?”, “名無しさん");
console.log(name);

関数:複数の処理

function 関数名(){
処理
}

function hello(name){
     console.log(“hello” + name);
}
hello(“Tom”);


function hello(name){
     return “hello” +name;
} 
var greet = hello(“Tom”);
console.log(greet);

ローカル変数

function hello(name){
     var msg = “hello” +name; //ローカル変数
     return msg;
} 
var greet = hello(“Tom”);
console.log(greet);



var hello = function(name){ // 無名関数、匿名関数
     var msg = “hello” +name; //ローカル変数
     return msg;
} ;
var greet = hello(“Tom”);
console.log(greet); 

即時関数

(function hello(name){
     console.log(“hello” + name);
} )(“Tom”);

即時関数にすることで、変数をローカル変数にすることが出来る。
複雑なコードを書く際に、安全に変数を使うことが出来る。

setInterval,setTimeout

setInterval

前の処理が終わったかどうか関係無しに次の処理を始めてしまう。->クラッシュしてしまう

     var i =0;
function show(){
     console.log(i++);
}
setInterval(function(){
     show();
}, 1000);

setInterval

前の処理が終わったかどうかを加味する。->繰り返し処理でよく使われる

    var i =0;
function show(){
     console.log(i++);
}
setInterval(function(){
     show();
}, 1000);

ループ処理

   var i =0;
function show(){
     console.log(i++);

     setInterval(function(){
          show();
     }, 1000); 
}
show();

3回表示でストップ

 var i =0;
function show(){
     console.log(i++);

     var tid = setInterval(function(){
          show();
     }, 1000); 
     if(i > 3){
     clearTimeout(tid);
     }
}
show(); 

配列

配列:グループ化されたデータ

var score_1 = 100, score_2 = 200;

var score = [100, 300, 500];
console.log(score[0]);
score[2]=400;
console.log(score);

var m =[
          [1, 2, 3],
          [4, 5, 6]
];

console.log(m[1][1]);

オブジェクト

 オブジェクト
      名前と値
var user ={
     email: “email@gmail.com”, //プロパティ
     score:80
};
console.log(user[“email”]);
console.log(user.email);
user.score = 100;
console.log(user);

メソッド

var user ={
     email: “email@gmail.com”, //プロパティ
     score:80
     greet: function(name){ // メソッド
               console.log(“hello,” + name + “from” + this.email);
               }
}; 

user.greet(“Tom”);

Stringオブジェクトの使用

 組み込みオブジェクト

 -String
-Array
-Math
-Date

どういうobjectがあるかはmdnへ。

var s = new String(“taguchi”);
var s = “taguchi”; //文字列リテラル

文字列リテラルと文字列オブジェクトは別物であるが、文字列リテラルにメソッドやプロパティをつけるとjavascriptが文字列オブジェクトを利用しようと解釈してくれるため、実行される。

console.log(s.length); //文字数を取り出す
console.log(s.replace(“t”,”T”));  //文字を取り替える
console.log(s.substr(1.3));     //文字も一部を取り出す

Arrayオブジェクトの使用

var a =new Array(100, 300, 200);
//var a =[100, 300, 200]

console.log(a.length);//要素の個数
//unshift -> array <- push     要素を追加
//shift <- arry -> pop     要素の削除
a.push(500);
console.log(a);

a.splice(1, 2, 800, 1000); //要素を途中に追加(削除)
console.log(a)

Math,Dateオブジェクトの使用

Mathオブジェクト

 console.log(Math.PI);     //π
    console.log(Math.ceil(5.3));     //切り上げ
    console.log(Math.floor(5.3));     //切り捨て
    console.log(Math.round(5.3));     //四捨五入
    console.log(Math.random());      //0~1のランダムな数字

Dateオブジェクト

var d = new Date();
//var d =new date(2014, 1, 11, 10, 20, 30);
console.log(d.getFullYear()); //年
console.log(d.getMonth());     //月(ただし、1月が0)
console.log(d.getTime);     //1970/1/1からの経過ミリ秒

DOMとは?

console.dir(window); //オブジェクトのプロパティを表示する
console.log(window.outHeight);
window.location.href = ‘http://dotinstall.dom'; //任意のページにリンクする

window.document -今開いているページ

document object model (DOM)

var e = document.getElementById(‘msg’);
e.textContent = ‘hello!’;     //テキストを書き換える
e.style.color =‘red’;     //スタイルを書き加える
e.className = ‘myStyle’;     //スタイルを適用する

var greet = document.createElement(‘p’),
     text = document.createTextNode(‘hello world’);
document.body.appendChild(greet).appendChild(text);
//appendChild 子要素の一番下に追加

イベントを設定する

ボタンを押すたびに要素を追加

<button id =“add”>Click!</button>

document.getElementById(‘add’).addEventListener(‘click’, function(){
     var greet = document.createElement(‘p’),
     text = document.createTextNode(‘hello world’);
document.body.appendChild(greet).appendChild(text); 
});
7
6
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
7
6