0
1

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.

javascriptメモ

Last updated at Posted at 2020-05-16

概要

javascript初めてなので、公式?を見ながら基本文法の確認した。

保存

//モジュール化されたJavaScriptファイル
const { NearestScanner } = require('@toio/scanner')

// 制御フロー
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Loops_and_iteration
function test_1a(){
let x = 0;
console.log(ループ開始前のxの値: ${x});
while (x < 10) {
console.log(x);
x += 1;
}
console.log(ループ終了後のxの値: ${x});

for (let step = 0; step < 5; step++) {
// 値が 0 から 4 まで計 5 回実行される
console.log('一歩西に歩く');
}
}

function test_1b(){

fruittype ='Apples'
switch (fruittype) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Apples':
console.log('Apples are $0.32 a pound.');
break;
default:
console.log(Sorry, we are out of ${fruittype}.);
}
console.log("Is there anything else you'd like?");

}

function test_1c()
{
let condition = true
let t_val = 10
if (condition) {
t_val = 1
}else if (condition == false) {
t_val = 2
}else {
t_val = 3
}
}

function test_1d()
{
let x = 0;
let z = 0;

labelCancelLoops:

while (true) {
console.log('外側のループ: ' + x);
x += 1;
z = 1;
while (true) {
console.log('内側のループ: ' + z);
z += 1;
if (z === 3 && x === 3) {
break labelCancelLoops;
} else if (z === 3) {
break;
}
}
}

}

function test_1(){
test_1a()
console.log('------------------------------');
test_1b()
console.log('------------------------------');
test_1c()
console.log('------------------------------');
test_1d()
console.log('------------------------------');

}

//https://www.sejuku.net/blog/61660
//【JavaScript入門】exitの代わりにtry catchでプログラムを終了する
function test2(){

const flag = true;
try {
if (flag) {
throw new Error('終了します');
}
console.log('実行されないコード');
} catch (e) {
console.log(e.message);
}
}

//--------------------------------------------
//変数

//構造体の代わり
function Position(x, y) {
this.x = x;
this.y = y;
}

/*
複数行のコメントアウト:入れ子のコメントは できない。

JavaScript は大文字と小文字を区別し、また Unicode 文字セットを使用しています。

文が単独の行で書かれている場合、文の後にセミコロンは必要ではありません。
*/
function test_3a(){
// strict モードも存在する
var val1 = 1
const flag = true
const val100 = 100

let local_val = 100; //ブロックスコープのローカル変数を宣言し

let szName ="APPLE"
let szNameKANJI ="漢字UTFらしい"
console.log(szNameKANJI);

//配列
const arr = [3, 5, 7];
// inとofの違い
for (let i in arr) {
console.log(i); // "0", "1", "2", "foo" が出力される
}
for (let i of arr) {
console.log(i); // 3, 5, 7 が出力される
}
//配列
var array = [];
array.push('hoge')
array.push('fuga')

async function testList() 
{
  var aData  = [];
  aData.push([1,1])
  aData.push([10,1])
  aData.push([10,10])
  aData.pop()  // [10,10]は消える
  aData.push([100,100])
  console.log(aData)
}

//DICT,連想配列
var mycar = {make: "Honda", model: "Accord", year: 1998};
console.log(mycar);
console.log(mycar['make'] +" "+ mycar['model'] +" "+ mycar['year'] );

var obj = {};
obj['hoge'] = 'moge';
console.log(obj['hoge']);

// //構造体
console.log("構造体") // Position {x: 0, y: 1}

//JavaScriptには俗に「構造体」と呼ばれるものはありません。(ないよね?)
console.log(new Position(0, 1)); // Position {x: 0, y: 1}
let t_pos = new Position(9, 99)
console.log(t_pos.x)

//console.log(Position(0, 1)); // undefined

}

function test_3(){
test_3a()
}

//--------------------------------------------

// 他の関数は非 Strict Mode になる。
// 'use strict';
//
/* Strict Mode 関数 */
function strict() {
// 関数レベル strict mode 文法
'use strict';
function nested() { return "ここでも Strict Mode."; }
return "Strict Mode 関数 " + nested();
}

function test_4(){
let result = strict()
console.log(result)
//notStrict()
}

//--------------------------------------------
function square(number) {
return number * number;
}

function test_5a(val) {
val = val + 1
}
function test_5b(arr) {
arr[0] = 99
}

function test_5c(theObject) {
theObject.make = "Toyota";
}

//関数呼び出し

function test_5b(){
var myFunc;
//local関数定義
myFunc = function(theObject) {
theObject = "Toyota"
return theObject
}

console.log(myFunc());

}

function loop(x) {
if (x >= 10) // "x >= 10" が終了条件 ("!(x < 10)" と同等)
return x;
// 何らかの処理を行う
return loop(x + 1); // 再帰呼出し
}

function multiply(a, b = 1) {
return a*b;
}

// https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Functions
function Person() {
var self = this; // self の代わりに that を選ぶ人もいます。
// どちらか一方を選び、そちらだけを使うようにしましょう。
self.age = 0;

// タイマー処理みたい
setInterval(function growUp() {
// このコールバックは、その値が期待通りのオブジェクトを指す
// 変数 self を参照している。
self.age++;
console.log(self.age )

}, 1000);
}

function test_5a(){
console.log("square " + square(2))

// プリミティブなパラメータ(数値など)は値渡しで関数に渡されます。
let t_val = 2
test_5a(t_val)
console.log("引数の参照、値渡しの確認: 2を関数内で+1してreturn -> " + t_val)

const arr = [3, 5, 7];
console.log("関数呼び出し前" + arr)
test_5b(arr)
console.log("関数で配列の値を変更" + arr)

// デフォルト引数
multiply(5); // 5

}

function test_5c(){

var p = new Person();
//p.setInterval()
console.log("new Person " + p.age )

}

// 関数呼び出し
function test_5(){
test_5b()

t_x = loop(0) // 再帰
console.log("再帰の結果 " + t_x)

test_5c()

}

//--------------------------------------------
// 数の表現、NULL
function JSClock() {
var time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
var temp = '' + ((hour > 12) ? hour - 12 : hour);
if (hour == 0)
temp = '12';
temp += ((minute < 10) ? ':0' : ':') + minute;
temp += ((second < 10) ? ':0' : ':') + second;
temp += (hour >= 12) ? ' P.M.' : ' A.M.';
return temp;
}

function test_6a()
{
//1E3 // 1000
//2e6 // 2000000
//0.1e2 // 10

let val = 0XA
console.log( val )
val = 1E3
console.log( val )
val = 0.1e2 //
console.log( val )
val = 2e3 // 2x 10^3
console.log( val )

// MAX_MIN
var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;
console.log( biggestNum )

// 文字列から数字
val = Number.parseInt("5155")
console.log( val )

//deg=rad∗(180/π)
//rad = deg * PI / 180

console.log( Math.PI )

let rad_val = 0
rad_val = 90 * Math.PI / 180
console.log( Math.sin(rad_val) )

//日付

var Xmas95 = new Date("December 25, 1995");
var today = new Date();
console.log( today )

}

function test_6()
{
test_6a()
console.log( JSClock() )
}

function test_7a()
{
var arr = [42]; // 42という数の要素を
// 1個だけ持つ配列が作られる。

var arr = Array(42); // 要素がなく、arr.length が
// 42に設定された配列が作られる。
// 以下のコードと同様。
var arr = [];
arr.length = 42;

let myVar = "moge"
var myArray = new Array('Hello', myVar, 3.14159);
console.log( myArray )

var cats = [];
cats[30] = ['Dusty'];
console.log("length")
console.log(cats.length); // 31

}

// 多次元配列
function test_7b()
{
var a = new Array(4);
for (i = 0; i < 4; i++) {
a[i] = new Array(4);
for (j = 0; j < 4; j++) {
//a[i][j] = '[' + i + ', ' + j + ']';
a[i][j] = i*4+j
}
}
console.log(a); // 31

}

//https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Indexed_collections
//型付き配列
function test_7c()
{

}

function test_7()
{

test_7a()
test_7b()
test_7c()
}

// map
function test_8a()
{
var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');
sayings.set('elephant', 'toot');
sayings.size; // 3
sayings.get('fox'); // undefined
sayings.has('bird'); // false
sayings.delete('dog');
sayings.has('dog'); // false

for (var [key, value] of sayings) {
console.log(key + ' goes ' + value);
}
// "cat goes meow"
// "elephant goes toot"

sayings.clear();
sayings.size; // 0

}
function test_8()
{

test_8a()
}

//プロパティの列挙
function showProps(obj, objName) {
var result = '';
for (var i in obj) {
// obj.hasOwnProperty() はオブジェクトのプロトタイプチェーンからプロパティを絞り込むために使用しています
if (obj.hasOwnProperty(i)) {
//result += objName + '.' + i + ' = ' + obj[i] + '\n';
result += i + ",";
}
}
return result;
}
// Object型
function test_9a()
{
var myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;
//console.log(myCar)

let result = showProps(myCar, "Mustang");
console.log("--")
console.log(result)

}
//コンストラクタ関数
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}

function test_9b()
{
var mycar = new Car('Eagle', 'Talon TSi', 1993);
console.log(mycar)
}

function test_9c()
{
console.log("------------- test_9c -------------")

function Employee() {
this.name = '';
this.dept = 'general';
}

function Manager() {
Employee.call(this);
this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor = Manager;

function WorkerBee() {
Employee.call(this);
this.projects = ["A", "B", "C"];
}
WorkerBee.prototype = Object.create(Employee.prototype);
WorkerBee.prototype.constructor = WorkerBee;

var jim = new Employee;
var bee = new WorkerBee;
var boss = new Manager;

console.log(jim)
console.log(bee)
console.log(boss)

}

//クラスとはちがうのか -> 「JavaScript は、クラスではなく、プロトタイプに基づいたオブジェクトベースの言語です」
function test_9()
{
try {
test_9a()
test_9b()
test_9c()

console.log("------------- end of test9 -------------")

let val = 1
val = val / 0  //例外発生しないみたい。
throw new Error('終了します');

} catch (e) {
console.log("in catch");
console.log(e.message);
}
}
async function main() {
console.log(in main -----------------)
test_9()
console.log(out main ---------------------)
}

main()

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?