戻る

列挙型
enumのような定数の代わりとなる方法のサンプルです。

1オブジェクトで定数を定義
2freezeを使ったオブジェクトの定数を定義
3Symbolを使ったユニークキー

オブジェクトで定数を定義
連想配列を一つのオブジェクトまとめる方法です。
書き換えが可能な方法です。

問題
答えを入力してください。



copy
//オブジェクトを使用した列挙型を定義します
const data1 = {
	ok:"正解",
	ng:"不正解",
	end:"問題はこれ以上ありません。",
	index:0//使用中のインデックス
};
//問題に使用する数字
const aryNum1=[2,3,5];//1個目の数字
const aryNum2=[4,1,6];//2個目の数字
//問題の出題数を表示
displayProblemNo("no1", data1.index + 1);
//問題を出力
printCalcProblem();
const btn1 = document.getElementById("btn1");
btn1.addEventListener("click", () => 
{
	//インデックスが3問目を超えているケース
	if(data1.index==3)
	{
		alert(data1.end);
		return;
	}
	//計算を判定
	judgeCalc();
	if(data1.index<3)
	{
		//問題の出題数を表示
		 displayProblemNo("no1", data1.index + 1);
		//問題を出力
		printCalcProblem();
	}
});
//問題の出題数を表示
function displayProblemNo(id, no)
{
	const obj =document.getElementById(id);
	obj.innerText = no + "問目";
}
//問題を出力
function printCalcProblem()
{
	const obj =document.getElementById("p1");
	obj.innerText = String(aryNum1[data1.index]) + " + " + String(aryNum2[data1.index]);
}
//計算を判定
function judgeCalc()
{
	let result = 0;
	//ユーザーの入力した結果を取得
	const obj =document.getElementById("ans1");
	result = obj.value;
	//たし算の結果とユーザーの入力した数字との判定
	if(Number(aryNum1[data1.index] + aryNum2[data1.index]) == result)
	{
		alert(data1.ok);//正解
	}
	else
	{
		alert(data1.ng);//不正解
	}
	data1.index++;//次のデータを参照するためインクリメントします
}
このサンプルは3個の問題を出題しています。
3個を答えたら、「問題はこれ以上ありません。」というメッセージを表示し
これ以上実行できないようにしています。

//オブジェクトを使用した列挙型を定義します
const data1 = {
  ok:"正解",
  ng:"不正解",
  end:"問題はこれ以上ありません。",
  index:0//使用中のインデックス
};

オブジェクトを作り、その中に連想配列を使用しています。
そのため、内部の値は変更することができます。
列挙型の定数として使用したい場合は、下記で説明するfreezeを使いますが、
オブジェクトの仕組みを使用して、必要な部分を変数として用いることができます。
今回はオブジェクト内のindexを問題のインデックスとして判定等に使用しています。

freezeを使ったオブジェクトの定数を定義
連想配列を一つのオブジェクトまとめる方法です。
書き換えが不可能な方法です。
問題
何文字か答えてください。


copy
//オブジェクトを使用した列挙型を定義します
const data2 = Object.freeze({
	ok:"正解",
	ng:"不正解",
	end:"問題はこれ以上ありません。",
	count:3//問題個数
});
//問題に使用する文字列
const aryData=["word","water","problem"];
let index = 0;
//問題の出題数を表示
displayProblemNo("no2", index + 1);
//問題を表示
displayProblemString();
const btn2 = document.getElementById("btn2");
btn2.addEventListener("click", () => 
{
	//インデックスが問題要素数を超えたケース
	if(index==data2.count)
	{
		alert(data2.end);
		//freezeを使ったオブジェクトの値を変更するテスト
		checkChangeValue();
		return;
	}
	//文字数を判定
	judgeLength();
	//次の問題が存在するケースは下記の処理を実行します
	if(index < data2.count)
	{
		//問題の出題数を表示
		displayProblemNo("no2", index + 1);
		//問題を出力
		displayProblemString();
	}
});
//freezeを使ったオブジェクトの値を変更するテスト
function checkChangeValue()
{
	try{
		data2.count = 0;//変更処理をしてみます
		alert("ステップが実行されました");
	}catch{
		alert("catch:エラーになった場合は、ここを通ります");
	}finally{
		alert("finally");
		alert("data2.countの現在の値:"+data2.count);
	}
}
//文字数を判定
function judgeLength()
{
	let result = 0;
	//ユーザーの入力した結果を取得
	const obj =document.getElementById("ans2");
	result = obj.value;
	//問題の文字列の長さを判定
	if(aryData[index].length == result)
	{
		alert(data1.ok);//正解
	}
	else
	{
		alert(data1.ng);//不正解
	}
	index++;//次のデータを参照するためインクリメントします
}
//問題を表示
function displayProblemString()
{
	const obj =document.getElementById("p2");
	obj.innerText = aryData[index];
}
//問題の出題数を表示
function displayProblemNo(id, no)
{
	const obj =document.getElementById(id);
	obj.innerText = no + "問目";
}
//オブジェクトを使用した列挙型を定義します
const data2 = Object.freeze({
  ok:"正解",
  ng:"不正解",
  end:"問題はこれ以上ありません。",
  count:3//問題個数
});
「Object.freeze」を使用すると内部で実装した連想配列の値を変更することができません。
このメリットとして複数人のプロジェクトで開発をしている場合、
オブジェクトの値を書き換えてしまう実装ミスを減らすことができます。
このサンプルでは下記の判定により、「Object.freeze」を使用したことにより
値の書き換えの変更ができない結果を実行したものです。
//freezeを使ったオブジェクトの値を変更するテスト
function checkChangeValue()
{
  try{
    data2.count = 0;//変更処理をしてみます
    alert("ステップが実行されました");
  }catch{
    alert("catch:エラーになった場合は、ここを通ります");
  }finally{
    alert("finally");
    alert("data2.countの現在の値:"+data2.count);
  }
}
[実行結果]
ステップ alert結果
(1) ステップが実行されました
(2) finally
(3) data2.countの現在の値:3

data2.count = 0;
ここで値の書き換えを実行しました。
しかし、alertの結果を確認してもわかるように変更されているないことがわかります。
書き換えが不可能であることがわかります。


Symbolを使ったユニークキー
SymbolはES6(ECMAScript 2015)で導入された仕組みです。
一意で不変な値を表すプリミティブ型として使われます。





copy
//symbolの変数との比較結果
const data3 ={
	ok1:Symbol(1),
	ok2:Symbol(1),
};
const btn3 = document.getElementById("btn3");
btn3.addEventListener("click", () => 
{
	if(data3.ok1.valueOf() === 1)
	{
		alert("一致");
	}
	else
	{
		alert("不一致");
	}
});
//symbolで同じ変数同士の比較結果
const btn4 = document.getElementById("btn4");
btn4.addEventListener("click", () => 
{
	if(data3.ok1 == data3.ok1)
	{
		alert("一致");
	}
	else
	{
		alert("不一致");
	}
});
//symbolで変数名が異なる比較結果
const btn5 = document.getElementById("btn5");
btn5.addEventListener("click", () => 
{
	if(data3.ok1 == data3.ok2)
	{
		alert("一致");
	}
	else
	{
		alert("不一致");
	}
});
valueOf()
SymbolオブジェクトはvalueOf()メソッドを実行することで、その中に格納されている値を返すことできます。

javascriptの列挙型(オブジェクトで定義)でSymbolを使用して定義した値と
プリミティブな値(数字や文字列など)と比較した場合、通常は一致しません
Symbolは一意な識別子であり、プリミティブな値とは異なる型として扱われるためです。
厳密な比較(===)でも厳密でない比較(==)でもfalseを返すためです。

[ボタンの実行結果]
ボタン名 alert結果
symbolの変数との比較結果 不一致
symbolで同じ変数同士の比較結果 一致
symbolで変数名が異なる比較結果 不一致


戻る
back

Enumerations
Here's an example of an alternative to enum-like constants.

1Define constants with objects
2Define constants with objects using freeze
3Unique key using Symbol

Define constants with objects
This is a way to combine associative arrays into one object.
This is a method that allows you to rewrite.

Question
Enter your answer.



copy
//Define an enumeration type using an object
const data1 = {
	ok:"correct",
	ng:"incorrect",
	end:"no more problem",
	index:0//Indexes in use
};
//Numbers used in the question
const aryNum1=[2,3,5];//First number
const aryNum2=[4,1,6];//Second number
//Show number of questions
displayProblemNo("no1", data1.index + 1);
//Print the problem
printCalcProblem();
const btn1 = document.getElementById("btn1");
btn1.addEventListener("click", () => 
{
	//Cases where the index is greater than the third question
	if(data1.index==3)
	{
		alert(data1.end);
		return;
	}
	//Evaluate the calculation
	judgeCalc();
	if(data1.index<3)
	{
		//Show number of questions
		 displayProblemNo("no1", data1.index + 1);
		//Print the problem
		printCalcProblem();
	}
});
//Show number of questions
function displayProblemNo(id, no)
{
	const obj =document.getElementById(id);
	obj.innerText = "No:"+no ;
}
//Print the problem
function printCalcProblem()
{
	const obj =document.getElementById("p1");
	obj.innerText = String(aryNum1[data1.index]) + " + " + String(aryNum2[data1.index]);
}
//Evaluate the calculation
function judgeCalc()
{
	let result = 0;
	//Get the result of the user's input
	const obj =document.getElementById("ans1");
	result = obj.value;
	//Check whether the result of the addition is the same as the number entered by the user
	if(Number(aryNum1[data1.index] + aryNum2[data1.index]) == result)
	{
		alert(data1.ok);//correct
	}
	else
	{
		alert(data1.ng);//incorrect
	}
	data1.index++;//Increment to reference the next data
}
This sample asks three questions.
After you answer all three questions, the message "There are no more questions" is displayed and you cannot continue.

//Define an enumeration using an object
const data1 = {
  ok:"correct",
  ng:"incorrect",
  end:"no more problem",
  index:0//Indexes in use
};

An object is created and an associative array is used within it.
Therefore, the internal values ​​can be changed.
If you want to use it as an enumeration constant, use freeze, which is explained below,
You can use the object mechanism to use the parts you need as variables.
In this case, the index within the object is used as the problem index for judgment, etc.


Defining constants for objects using freeze
This is a method to combine associative arrays into one object.
This method cannot be rewritten.
Question
Please answer with a few characters.


copy
//Define an enumeration type using an object
const data2 = Object.freeze({
	ok:"correct",
	ng:"incorrect",
	end:"no more problem",
	count:3//problme count
});
//String to use in question
const aryData=["word","water","problem"];
let index = 0;
//Show number of questions
displayProblemNo("no2", index + 1);
//display problem
displayProblemString();
const btn2 = document.getElementById("btn2");
btn2.addEventListener("click", () => 
{
	//Cases where the index exceeds the number of problem elements
	if(index==data2.count)
	{
		alert(data2.end);
		//Testing changing object values ​​using freeze
		checkChangeValue();
		return;
	}
	//Determine the number of characters
	judgeLength();
	//If the following problem exists, perform the following steps:
	if(index < data2.count)
	{
		//Show number of questions
		displayProblemNo("no2", index + 1);
		//Print the problem
		displayProblemString();
	}
});
//Testing changing object values ​​using freeze
function checkChangeValue()
{
	try{
		data2.count = 0;//try to make the change
		alert("Step performed");
	}catch{
		alert("catch:If get an error, go here");
	}finally{
		alert("finally");
		alert("data2.count current value:"+data2.count);
	}
}
//Determine the number of characters
function judgeLength()
{
	let result = 0;
	//Get the result of the user's input
	const obj =document.getElementById("ans2");
	result = obj.value;
	//Determine the length of the string in question
	if(aryData[index].length == result)
	{
		alert(data1.ok);//correct
	}
	else
	{
		alert(data1.ng);//incorrect
	}
	index++;//Increment to reference the next data
}
//display problem
function displayProblemString()
{
	const obj =document.getElementById("p2");
	obj.innerText = aryData[index];
}
//Show number of questions
function displayProblemNo(id, no)
{
	const obj =document.getElementById(id);
	obj.innerText = "No:" + no;
}
//Define an enumeration type using an object
const data2 = Object.freeze({
  ok:"Correct",
  ng:"Incorrect",
  end:"No more questions.",
  count:3//Number of questions
});
When you use "Object.freeze", you cannot change the values ​​of the internally implemented associative array.
The advantage of this is that when developing a project with multiple people,
it reduces implementation errors that cause object values ​​to be overwritten.
In this sample, the following judgment was made, and the result of using "Object.freeze"
would not allow the value to be overwritten.
//Test changing object value using freeze
function checkChangeValue()
{
  try{
    data2.count = 0;// Try the change process
    alert("Step was executed");
  }catch{
    alert("catch:If an error occurs, go through here");
  }finally{
    alert("finally");
   alert("Current value of data2.count:"+data2.count);
  }
}
[Execution result]
Step alert result
(1) Step executed
(2) finally
(3) Current value of data2.count: 3

data2.count = 0;
Here, we rewrote the value.
However, as you can see from the alert result, no changes have been made.
We can see that rewriting is not possible.


Unique key using Symbol
Symbol is a mechanism introduced in ES6 (ECMAScript 2015).
It is used as a primitive type to represent a unique and immutable value.





copy
//The result of comparing symbol with the variable
const data3 ={
	ok1:Symbol(1),
	ok2:Symbol(1),
};
const btn3 = document.getElementById("btn3");
btn3.addEventListener("click", () => 
{
	if(data3.ok1.valueOf() === 1)
	{
		alert("equal");
	}
	else
	{
		alert("not equal");
	}
});
//Comparison result between variables with the same symbol
const btn4 = document.getElementById("btn4");
btn4.addEventListener("click", () => 
{
	if(data3.ok1 == data3.ok1)
	{
		alert("equal");
	}
	else
	{
		alert("not equal");
	}
});
//Comparison result where the variable name is different for symbol
const btn5 = document.getElementById("btn5");
btn5.addEventListener("click", () => 
{
	if(data3.ok1 == data3.ok2)
	{
		alert("equal");
	}
	else
	{
		alert("not equal");
	}
});
valueOf()
Symbol objects can return the value stored in them by executing the valueOf() method.

Values ​​defined using Symbol in JavaScript enumerations (defined in objects)
When compared with primitive values ​​(numbers, strings, etc.), they usually do not match.
This is because Symbols are unique identifiers and are treated as a different type than primitive values.
This is because both strict (===) and non-strict (==) comparisons return false.

[Button execution results]
Button name Alert result
Comparison result with symbol variable Mismatch
Comparison result with same variable in symbol Match
Comparison result with different variable name in symbol Mismatch


back



著作権情報
ホームページおよびアプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。