是否可以在JavaScript中创建新的数据类型?

是的,您可以使用类的概念。如果要检查实际数据类型,则可以使用instanceof。

instanceof讲述数据类型。这是示例JavaScript代码,将简要说明如何创建新数据类型以及如何检查数据类型。在这里,我将提供自定义实现以检查数据类型。

示例

以下是代码-

//creating the class
class Game {
   constructor(gameName) {
      this.gameName = gameName;
   }
}
//创建一个对象
const ticTacToe = new Game("TicTacToe");
//检查数据类型。
function dataTypeBelongsTo(object) {
   if (object instanceof Game)
      return "Game";
   return typeof object; 
}
console.log("The ticTacToe is the object of Game class=" + (ticTacToe instanceof Game));
console.log("The data Type of ticTacToe is =" + dataTypeBelongsTo(ticTacToe));
console.log("The data Type Candy Cash is =" + dataTypeBelongsTo("Cady Cash"));

要运行上述程序,您需要使用以下命令-

node fileName.js.

在这里,我的文件名为demo288.js。

输出结果

这将在控制台上产生以下输出-

PS C:\Users\Amit\javascript-code> node demo288.js
The ticTacToe is the object of Game class=true
The data Type of ticTacToe is =Game
The data Type Candy Cash is =string
猜你喜欢