javascript 構文

目次

エラー処理

'use strict';

宣言文

 

// 変数代入
let xx = "";
let xx = [];

// 定数代入
const yy = "";
const yy = [];

// index付の連想配列(多次元配列)
const point = {x: 100, y: 200};
const points = [
  {x: 10, y: 20},
  {x: 30, y: 40},
  {x: 50, y: 60}
]

// 連想配列に変数を使用
let username = 'masayan';
const arr = {name: username, cost: 200};

連想配列をソート

arr.sort(function(a, b) {
  if (a.cost < b.cost) {
    return -1
  }
  if (a.cost > b.cost) {
    return 1;
  }
  return 0;
});

for 構文

for (let i = 0; i < 5; i++) {
  console.log(i);
}

while 構文

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

if 構文

if (xx === 1) {
  console.log('1');
} else if {
  console.log('2');
} else {
  console.log('3');
}

switch 構文

switch (str) {
  case 'A':
    str += '1';
    break;
  case 'B':
    str += '2';
    break;
  case 'C':
    str += '3';
    break;
  default:
    str += other;
    break;
}

and 条件 構文

if (xx === 1 && name === 'masayan') {
  console.log('GOOD');
}

for 文をスキップ、終了 continue 、 break

for (let i = 1; i <= 10; i++) {
  if (i % 3 === 0) {
    continue; //スキップ
  }
  if (i === 7) {
    break; //終了
  }

  console.log(`Index : ${i}`);
}

関数呼び出し function

function test(str = "happy") {
  console.log(`------- ${str} ------`)  // 仮引数
}

test("masayan");
test("saiko");  //  実引数
test();

関数呼び出し アロー

const tasu = (a,b,c) => a+b+c;
const total = tasu(1,2,3) + tasu(4,5,6);
console.log(total);

foreach 構文

const scores = [10,20,30,40];
scores.forEach((score,index) => {
  console.log(`score ${index}: ${score}`)
});

map 関数

const prices = [60,120,140];
const updateprices = prices.map(price => price + 20);
console.log(updateprices);

split 関数

const t = '19:01:55'
console.log(t.split(':'));

代入

const [hour, minuts, second] = t.split(':');

小数点 切り上げ、切り下げ

console.log(Math.floor(avg)); // 小数点を切り下げ
console.log(Math.ceil(avg));  // 小数点を切り上げ
console.log(Math.round(avg)); // 小数点を切り下げ
console.log(avg.toFixed(3));  // 少数点3桁まで表示

ランダムな数値

console.log(Math.random());  // ランダムな0-1の数値を取得
console.log(Math.floor(Math.random() * 6) + 1);  // ランダムな1-6の数値を取得

メッセージボックス

alert('hello'); 
// Yes,Noのメッセージボックス表示
const ans = confirm('削除しますか?');
if (ans === true) {
  console.log('削除しました');
} else {
  console.log('キャンセルしました');
}

遅延

setInterval(showtime, 1000);
setTimeout(showtime, 1000);

大文字変換

const name = 'masayan';
console.log(name.toUpperCase());

try 関数

const int = 0;
try {
  console.log(int.toUpperCase());
} catch(e) {
  console.log(e);
}
console.log('compete');

アクション

// buttonをクリックしたときのアクション
document.querySelector('button').addEventListener('click', () => {});
// inputを取得
const colors = document.querySelectorAll('input');
// buttonをダブルクリックしたときのアクション
document.querySelector('button').addEventListener('dblclick', () => {});
// マウスを移動したときのアクション
document.addEventListener('mousemove', e => {});

文字列切り出し

str.substr(0, 5);

置換

// (aa -> bb)
str = str.split("aa");
str = str.join("bb");

割り算 あまり

double = a / b;
int = a % b;

べき乗

Math.pow(int, 2);
// 逆
Math.pow(int, 0.5))

文字列の位置を取得

str.indexOf('a');

最大値と最小値

Math.max.apply(null, array);
Math.min.apply(null, array);

文字列反転

str.split("").reverse().join("");

数値かチェック

isNaN(int);
Number.isInteger(value);

並び替え、ソート (arrayは配列)

array.sort();

文字列を数値に変換

parseInt(str);

円周率

Math.PI.toString();

絶対値

Math.abs(int);

重複削除

let arrfilter = arr.filter(function (x, i, self) {
  return self.indexOf(x) === i;
});

テキストファイル読み込み

html部分

<body>
  <form name="test">
    <input type="file" id="selectfile"><br>
    <textarea name="txt1" rows="10" cols="40" readonly></textarea>
    <textarea name="txt2" rows="10" cols="40" readonly></textarea>
    <textarea name="txt3" rows="10" cols="40" readonly></textarea>
  </form>
  <script src="js/main.js"></script>
</body>

js部分

// ファイル選択ボタンを代入
let btn = document.getElementById(“selectfile”);

// ボタンがクリックし、ダイアログでファイルが選択された場合の処理
btn.addEventListener(“change”,function(e){

// 初期化
document.test.txt1.value = ”;

// 選択したファイルを代入
let file = e.target.files;

// FileReader の作成
let reader = new FileReader();
// テキスト形式で読み込む
reader.readAsText(file[0]);

// 読込終了後の処理
reader.onload = function(ev){
// 読み込んだすべてのテキストを代入
let txt = reader.result;
// テキストを改行ごとに配列にする
let lines = txt.split(/\r?\n/);

// テキストを1行ごとにテキストエリアに表示
lines.forEach(line => {
document.test.txt1.value += line + “\n”;
});
}
},false);