Samples
J. JavaScript Examples:
These examples will allow you to put into practice the concepts learned in this manual. It will sustain you with an
A. Operators
Statement
It is about creating a simple function to add two numbers, which occur as arguments. The function will return the sum of both numbers.
The code
function fSum(sum1, sum2) {
let Result;
Result = sum1 + sum2;
return Result;
}
logger.warn('4 + 10 = ' + fSum(4, 10)); /* Show result */
Comments
In this simple example we create the function using the keyword function that follows the name in this case fSum. In parentheses, we write the names we give to the arguments that uses the function: Sum1 and Sum2 in the example. When we call the function in parentheses, we will write two values that will be saved in these variables.
We also see how to create a variable using the keyword var followed by the variable name, in the example Result. The symbol = is the operator assignment with which we save the sum in the variable Result.
Finally we use return to return the result to the program that uses the function fSum. The symbols /* and */ enclose any personal comment to clarify the program.
In the test body we will use logger.warn to show at the bottom (log) the result of the sum.
B. Arithmetic average
Statement
Create a function that calculates the arithmetic mean (data sum divided by number of values) of a set of numerical data that occur as arguments. The data number is variable.
The code
function fAverage() {
let total = 0, res, numDat, item;
numDat = arguments.length;
for (item = 0; item < numDat; item++) {
total += arguments[item];
}
res = total / numDat;
return res;
}
logger.warn(fAverage(3, 50, 40, 25, 10));
Comments
The function is created as usual with function. The variables that are going to be used are declared, on this occasion at the same time initialize the value of one of them, total, which will store the sum of the data.
We keep in Numdat the number of past arguments through the property length property arguments of the object function.
Through a loop for we travel the argument matrix and we are accumulating in total
The data passed to the function. Observe the use of the operator + = that adds to the content of the total variable the value of the element Arguments [Item].
Calculate the average by dividing total by the numDat and finally returns the result stored in res.
This code could be shorter but I preferred to detail it as much as possible to illustrate the use of operators and make the program clearer.
C. Greeting
Statement
This program will make you
The code
function greet(){
let vTime = new Date();
let hour, str = 'are the ';
with (vTime) {
hour = getHours();
str += hour + ':' + getMinutes() + ':' + getSeconds();
}
if (hour < 12) {
str = 'Good morning, ' + str;
} else if (hour < 18) {
str = 'Good afternoon, ' + str;
} else {
str = 'Good night, ' + str;
}
return str
}
logger.warn(greet());
Comments
In this example we use the object Date to determine the time of day, then we extract the time of the time object and build a string str with the time, minute and second of the day for greeting. The variable hour we compare it with 12 and 18 through statements if ... else nested.
If it is before 12 (time <12) greeting to write will be the string "Good morning, are the ..." followed by the full time that is stored in the variable str, if it is not before 12 we check if it is before the 18 if so, the chain is "good afternoon are the ..." and if any of the previous cases should be done at night.
Observe the use of the structure with that allows you to work with the elements of an object without having to write your name and the separator point (time.Getdate(), etc). Also note how to modify the variable str: endeavoring the prefix with the appropriate greeting (full time).
D. Random array
Statement
This simple example is about how to fill out a given length list, in this case 10, with random numbers between 0 and 20, all integers.
The code
function Fill(matrix) {
let long, value, ind;
long = matrix.length;
for (ind = 0; ind < long; ind++) {
value = Math.random()*20;
matrix[ind] = Math.round(value);
}
}
let list = new Array(10);
fill(list);
logger.warn(list);
Comments
In this program it is interesting to observe how the values given to the argument within the function remain at the end, so that the variable list before going through the function was empty and after running fill has values Random numericals.
This happens so because that argument is an object array, it is the only case in which JavaScript uses step from arguments by reference. Another point is that this function do not use return since it does not return any value. The rest of the code is very simple: a loop for () to scroll through the matrix and give values calculated with the method random of the object math rounded to the nearest integer using the method round.
E. Check e-mail 1
Statement
This is a function that can be quite useful to check email addresses. It's about seeing if an email address contains the @ and point in its place.
The code
function checkemail(email) {
let ind1, ind2, ind3;
ind1 = email.indexOf('@');
ind2 = email.indexOf('.');
ind3 = email.lastIndexOf('@');
if ((ind1<=0) || (ind2<ind1) || (ind3 != ind1)) {
return 'Is not correct';
} else {
return 'Correct';
}
}
let addr = 'javascript@adquio.com';
logger.warn(addr + ' ' + checkemail(addr));
addr = 'mal@adquio.pro@es';
logger.warn(addr + ' ' + checkemail(addr));
Comments
No comments to highlight.
F. Check E-mail 2
Statement
This is a function that can be quite useful to check email addresses. This is to see if an email address contains characters correct and follows the usual pattern : user@host , user and server may contain more alphanumeric characters (underscore) and (hyphen) .
The code
function checkMail(str) {
let plant = /[^\w^@^\.^-]+/gi;
if (plant.test(str)) {
alert(str + ' contains strange characters.');
} else {
plant = /(^\w+)(@{1})([\w\.-]+$)/i;
if (plant.test(str)) {
alert(str + ' is correct.');
} else {
alert(str + ' is not valid.');
}
}
}
Comments
The Checkmail() function first checks if there is a strange character for which it uses the regular expression: /[^\w^@^\.^-]+/gi, check if there is any non-alphanumeric character, or different from @, point or dash.
Once this has done this happens to check the structure of the string by other regular expression, in this case it checks that the string starts with an alphanumeric character (^ indicates here string start and \w alphanumeric characters) followed by similar ones, this Group must be followed by a single symbol at (@{1}) after which there may be any group of alphanumerication including the point or script ([\w\.-]) until reaching the end of the chain ($).
If you have any doubts, consult the descriptive section of regular expressions and dedicated to your methods.
G. Search within an array
Statement
This time we have a list of names and wish to determine if a particular name is on the list , and if so, what position is . If the name is not on the list the function must return a negative value.
The code
function SearchItem(list, value) {
let ind, pos;
for(ind = 0; ind < list.length; ind++) {
if (list[ind] == value) {
break;
}
}
pos = (ind < list.length)? ind : -1;
return (pos);
}
let list1 = new Array('John', 'Peter', 'Lewis', 'Mary', 'Julia');
let str = 'Mary';
let pos = SearchItem(list1, str);
if (pos >=0) {
logger.warn(str + ' is in position '+ pos );
} else {
logger.warn(str + ' is not on the list.');
}
Comments
The list is constructed as an array in which we store names. The variable str contains the name we want to search. The function works with two arguments: the list of names and the value to search, in it we make a loop to go through a variable list until you find the name searched, if we find it stop Loop with instruction break.
If the loop has finished without finding the name the variable ind will be equal to the array longiutd (remember that the indexes range from 0 to the length of the Less 1), while if the name has been found its value It will be less than that length ..
Observe the sentence after the loop: in pos We put the value of the ind if the name has been found and if we do not put -1, it is the abbreviated form to use a statement if...else.
H. Extract substring
Statement
We start from a text and we will see how to read a part of it. The part to read will be delimited by two labels one of the beginning and another of the end. The start label will be / and the end will be */*.
The code
function extract(text, LabelBeg, LabelEnd) {
let ind0, ind1, part = '';
ind0 = text.indexOf(LabelBeg);
if (ind0 >=0) {
ind1 = text.indexOf(LabelEnd);
if (ind1>ind0) {
part = text.substring(ind0 + LabelBeg.length, ind1);
}
}
return part;
}
let str = 'This string is the one that, /* in the example */, it is going to be processed';
logger.warn('String: ' + str);
logger.warn('String extracted.: ' + extract(str, '/*','*/'));
Comments
In this example we see how to extract from a text a part delimited by labels. First of all we look for the position of the start label, LabelBeg, which we save in ind0; If this label exists (ind0> = 0) we look for the end tag, LabelEnd, which must be after the start, so we compare (ind1> ind0). Finally, we extract the characters included between the end of the LbaleBeg (ind0 + length of LabelBeg) and the start of the LabelEnd using the substring method.
I. Creating objects
Statement
We are going to create an object used to represent an item from a store. The article will be characterized by a description, code and a price, and must allow the calculation of its corresponding tax.
The code
function tax() {
return Math.round(this.value * 0.21);
}
function total(red) {
let price = this.tax() + this.value;
price = price - price * red / 100;
return Math.round(price);
}
function obj_Article(desc, cod, price) {
this.desc = desc;
this.code = cod;
this.value = price;
this.tax = tax;
this.retail = total;
}
let item = new obj_article('USB Mouse', 'PerRt-01', 50);
logger.warn('Article: ' + item.desc + ' (' + item.code + ')');
logger.warn('Price: ' + item.value + ' €');
logger.warn('VAT: ' + item.tax() + ' €');
logger.warn('Sale price: '+ item.retail(10)+ ' € (Dto 10%)');
Comments
This example illustrates how to create a Object With its properties and methods. The function obj_Article is the object builder while the functions tax() and total(red) are methods for that object. The argument of the second indicates a possible discount.
These functions are simple arithmetic operations and require no further explanation. As to the builder properties (desc, code, value) are assigned directly using this to refer to the object itself.
For the methods it is done exactly the same but assigning functions(tax, total). We have a method that uses arguments and another without them, that is, this example presents all the possibilities in creating objects and could be the basis for creating a shopping list whose properties would be an object of the type defined here.