未加星标

JavaScript Enums Example

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

Greetings readers, in this tutorial, we will show how to use the javascript enumerations .

1. Introduction

JavaScriptis an object-oriented programming language that allows the client-side scripting to interact with a user and deliver the dynamic pages. Most web browsers including Google Chrome, Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera, etc. support it. The JavaScript scripting language includes:

Declaring variables Maintaining the retrieving values Defining and invoking functions Defining classes Load and use external modules Define event handlers And much more …. 1.1 Advantages of JavaScript Language

The pros of using the JavaScript scripting language are:

JavaScript is easy to learn It executes on client’s browser, so eliminates the server-side processing and be executed on any OS JavaScript can be used with any type of web page e.g.php, ASP.NET, Perl etc Web-page performance increases due to client-side execution JavaScript code can be minified to decrease the loading time from the server Many JavaScript-based application frameworks are available in the market to create Single page web applications e.g. AngularJS, ReactJS etc. 1.2 Disadvantages of JavaScript Language

The cons of using the JavaScript scripting language are:

No support for networking applications Does not have any multi-threading or multi-processing capabilities Does not allow the file reading and writing capabilities 1.3 JavaScript Enum Enum represents a fixed number of values (also known as constants ) in a programming language Offers, Consistency as developers does not worry about the exact value of the string Excellent exception handling Makes the code more stable, easy to read and less error-prone Syntax: enum WeekDay = { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; 2. JavaScript Enums Example

Here is a systematic guide for implementing this tutorial using the JavaScript language.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!


JavaScript Enums Example

Fig. 1: Application Project Structure

2.3 Project Creation

This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project .


JavaScript Enums Example

Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.


JavaScript Enums Example

Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.


JavaScript Enums Example

Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT .


JavaScript Enums Example

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javascript</groupId> <artifactId>JavaScriptEnum</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project> 3. Application Building

Let us create an application to understand the basic building blocks of this tutorial.

3.1 Define the HTML

Let us write a simple index page in the JavaScriptEnum/src/main/webapp/ folder. Add the following code to it:

index.jsp

<!------ JavaScript Enums Example ------> <div class="form-group"> <!-- What is Enum? --> <div id="enum-info-result"> <h4 class="text-primary font-weight-bold">Enums</h4> <ol class="text-info line-hgt"> <li>In a programming language, an enumerated type (also called <em>enumeration</em> or <em>enum</em>) is a data-type consisting of a set of named values considered elements.</li> <li>They behave like <strong>constants</strong> in a programming language.</li> <li>E.g. <pre>enum WeekDay = { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };</pre></li> </ol> </div> <!-- Direction selection drop-down --> <div id="code"> <h4 class="text-sucess">Code Snippet</h4><div> </div> <div class="col-sm-4"> <select id="dir_idx" class="form-control" onchange="sayDirection();"> <option selected="selected" value="-1" disabled>Select direction</option> <option value="UP">Up</option> <option value="DOWN">Down</option> <option value="LEFT">Left</option> <option value="RIGHT">Right</option> </select> </div> </div> </div> <div> </div> <!-- Result --> <h5 id="result" class="text-info"></h5> 3.2 Define the JavaScript function

Let us write a simple javascript function that shows the enum implementation in the javascript language. Add the following code to it:

JavaScript function

// Declaring enum const Direction = { UP: 'UP', DOWN: 'DOWN', LEFT: 'LEFT', RIGHT: 'RIGHT' }; function sayDirection() { var direction = document.getElementById("dir_idx").value; switch (direction) { case Direction.UP: document.getElementById("result").innerHTML = 'We are going up!'; break; case Direction.DOWN: document.getElementById("result").innerHTML = 'Heading all the way down. . .'; break; case Direction.LEFT: document.getElementById("result").innerHTML = 'Left not right!'; break; case Direction.RIGHT: document.getElementById("result").innerHTML = 'To the right.'; break; } } 3.3 First application

Complete the above steps and save the file. Let us see the sample code snippet.

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Index page</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script type="text/javascript"> // Declaring enum const Direction = { UP: 'UP', DOWN: 'DOWN', LEFT: 'LEFT', RIGHT: 'RIGHT' }; function sayDirection() { var direction = document.getElementById("dir_idx").value; switch (direction) { case Direction.UP: document.getElementById("result").innerHTML = 'We are going up!'; break; case Direction.DOWN: document.getElementById("result").innerHTML = 'Heading all the way down. . .'; break; case Direction.LEFT: document.getElementById("result").innerHTML = 'Left not right!'; break; case Direction.RIGHT: document.getElementById("result").innerHTML = 'To the right.'; break; } } </script> <style type="text/css"> #enum-info-result, #code, #result { margin-left: 16px; } .line-hgt { line-height: 2.0; } </style> </head> <body> <div class="container"> <h2 align="center" class="text-danger">JavaScript Enums Example</h2> <hr /> <!------ JavaScript Enums Example ------> <div class="form-group"> <!-- What is Enum? --> <div id="enum-info-result"> <h4 class="text-primary font-weight-bold">Enums</h4> <ol class="text-info line-hgt"> <li>In a programming language, an enumerated type (also called <em>enumeration</em> or <em>enum</em>) is a data-type consisting of a set of named values considered elements.</li> <li>They behave like <strong>constants</strong> in a programming language.</li> <li>E.g. <pre>enum WeekDay = { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };</pre></li> </ol> </div> <!-- Direction selection drop-down --> <div id="code"> <h4 class="text-sucess">Code Snippet</h4><div> </div> <div class="col-sm-4"> <select id="dir_idx" class="form-control" onchange="sayDirection();"> <option selected="selected" value="-1" disabled>Select direction</option> <option value="UP">Up</option> <option value="DOWN">Down</option> <option value="LEFT">Left</option> <option value="RIGHT">Right</option> </select> </div> </div> </div> <div> </div> <!-- Result --> <h5 id="result" class="text-info"></h5> </div> </body> </html> 4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server .


JavaScript Enums Example

Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL to display the application’s index page as shown in Fig. 7.

http://localhost:8082/JavaScriptEnum/

Server name (localhost) and port (8082) may vary as per your Tomcat configuration.


JavaScript Enums Example

Fig. 7: Index page

Users can select the values from the dropdown to show the relevant text from the enum constant as shown in Fig. 8.


JavaScript Enums Example

Fig. 8: Enumeration in JavaScript

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to create a simple application with the JavaScript language. Developers can download the sample application as an Eclipse project in thesection.

7. Download the Eclipse Project

This was an example of JavaScript Enums for the beginners.

Download

You can download the full source code of this example here: JavaScriptEnum

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

分页:12
转载请注明
本文标题:JavaScript Enums Example
本站链接:https://www.codesec.net/view/611765.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(10)