Skip to content

Objects

5. The objects:

A. Arrays

As objects that are, arrays possess their properties and predefined methods, which are expandable by the user. It is necessary to note that these methods and properties are those defined for Microsoft JavaScript 3.0. Netscape adds more methods in its version, but those defined here are common to both browsers.

Properties

length

As its name indicates this property, it returns the length of the array, that is, the number of items you can store. It's easy to use:

let list = new Array(50);
size = list.length; /*size would store the value 50 */
prototype

This is a very powerful property in the sense that allows us to add to the property array the properties and methods we want.

Array.protoype.descriptor = null;
days = new Array ('Monday', 'Tuesday', 'Wednesday', 'Thursday',  'Friday');
days.descriptor = 'Working days of the week';

In this example we have created a new property for the array object, the descriptor property that could be used to give you a title to the matrix.

Methods

concat(objArray)

Join the array object with the array that is passed as an argument and returns the result in a new array, without modifying the arrays that are concatenated.

join()

Convert the elements of an array into a string separated by the character indicated. The default separator is the comma.

let a = new Array('Hello', 'Good', 'morning');
logger.warn(a.join());
logger.warn(a.join(', '));
logger.warn(a.join(' + ')) ;

The departure of this program would be: Hello,Good,morning Hello, Good, morning Hello + Good + morning

reverse()

Invert the order of the elements of an array in the array itself, without creating a new one.

slice(ini, fin)

It extracts part of an array returning it into a new array object.

list = new Array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
sublist = list.slice(2, 6);
logger.warn(sublist.join());

In the Sublist example, it will contain the elements from the index 2 to 5 both inclusive, bone, 'c', 'd', 'e', 'f'. If the second argument is omitted, it is extracted to the last element of the array and if it is negative it is understood as counting from the end.

sort(rutord)

He ordered alphabet the elements of an array object. Optionally we can go as an argument a function to determine the order, this function has two arguments and will return a negative value if the first argument is less than the second, zero if they are equal and a positive value if the first argument is greater than the second. In Spanish this is necessary if we want the ñ and accentuated vowels to appear in their place.

B. Booleans: True or false

The Boolean or logic variables are those that can only take two values: true, true, and false, false. This type of variables is implemented in JavaScript as an object.

Methods

toString

If the value is false returns the "false" string and if it is true, it returns the "true" string

valueOf

Returns Boolean value( true o false )

Properties

constructor

Inherited from the generic object object, returns the reference to the constructor:

function Boolean() { [native code] }
prototype

It is a property used to assign new methods or properties, inherited from the object generic object. For example we can translate the valuestrue or false.

function valor () {
  return this.valueOf()?'cierto':'falso'
}


Boolean.prototype.valor = valor;
let item = new Boolean(false);
logger.warn(item.valor());

With this example we achieved that true is returned as the string "cierto" and false as the "falso" string.

C. Object Function

It allows the creation of functions, whether with name or anonymous. The creation of a function can be done by the traditional and common method to most programming languages:

function add(a, b) {
  return a + b;
}

Or mediate the well-known operator new :

add = new Function ('a', 'b', 'return a + b');

In any case, the function will be used in the same way:

logger.warn( add(90, 100));

Methods

The legacy of the object Object

Properties
arguments

It is an array that contains the arguments passed to the function. This property allows the use of functions with a variable number of arguments.

caller

It contains a reference to the function that called the current one.

constructor

Inherited from the class Object

D. Object Number

It is the object intended for handling data and numerical constants. It really is not usual to create objects of this type because JavaScript creates them automatically when necessary. However the syntax for its creation is the usual to any object:

mynumber = new Number(InitialValue);

The initial value is optional, if the object is not used is created with null value

Methods

The legacy of the object object

Properties

In addition to the inherited of the object object Number possesses the following properties:

MAX_VALUE

Indicates the maximum value usable by JavaScript, currently 1.79E + 308.

MIN_VALUE

Indicates the minimum value usable by JavaScript, currently 2.22E-308.

NaN

A constant used to indicate that an expression has returned a non-numeric value (Not a Number). NAN can not be compared using the usual logical operators, to see if a value is equal to NAN must use the built-in function isnan

NEGATIVE_INFINITY

A constant to indicate infinity negative, that is, a value below the min_value

POSITIVE_INFINITY

A constant to indicate infinite positive, that is, a value superior to the Max_Value with a negative sign

E. Object Object

Yes: there is an object called object from which all objects from JavaScript, the predefined and those defined by the user are derived. This means that the objects used in JavaScript inherit the properties and methods of object.

Métodos

toString

Returns a string depending on the object in which it is used

Object String returned by the method
Array Array elements separated by comma
Boolean If the value is false returns "false" if it does not return "true"
Function The string "function function_name(arguments){[code]}"
Number Textual representation of the number
String The value of the string
Default "[object Name_Of_object]"
valueOf

Returns the value of the object depending on the object in which it is used

Object Value that returns the method
Array A string formed by elements separated by comma
Boolean The Boolean value (true o false)
Date The date as the number of milliseconds from the 1/1/1970, 00:00
Function The function itself
Number The numerical value
String The string
Default The object itself

Properties

constructor

This property contains a reference to the function that creates the instances of the particular object. For instance:

x = new String('Helllo');
//In this case x.constructor will contain
// function String() { [native code] }
prototype

It is a property used to assign new methods or properties to an object, elements that will be inherited by the different instances of that object. Example:

Array.prototype.nameType = 'matrix';
list = new Array(9);
logger.warn(list.nameType);
//Write the word 'matrix' what is nameType
//that we have given for the array object

F. Object Regular Expession

JavaScript uses this object to work with regular expressions patterns, these patterns are created as any other object through direct initialization or through the constructor new regexp(), as we can see in the example:

let mypattern = /^[aeiou]/gi
let mypattern2 = new RegExp('^[aeiou]', 'gi')

Both forms lead to the same pattern, in this example define words that start with a vowel. The pattern can carry modifiers or flags to nuance the way of searching, in the example two: g i These modifiers have the following meanings:

flags Meaning
g Explore the full string
i Do not distinguish uppercase tinus
m It allows us to use several ^y $ In the pattern
s Includes the line break in the Point Wildcard .
x Ignore spaces in the pattern

These patterns have a total three methods exec(), test(), compile() In addition to the aforementioned methods of the String object that also use patterns such as: Match(), Replace(), Search() and Split().

The only property that works on these objects is the Source that reflects the contents of the pattern. In the pattern, characters or groups of characters enclosed in parentheses may appear, then we can use an index to refer individually to the content of those parentheses.

For example we are going to replace by a - all the digits located after a letter in the string to be explored.

let strexp = '234879x089h9y7';
let pattern = /([a-z])(\d)/ig;
logger.warn(strexp);
cadexp = strexp.replace(pattern, '$2-');
logger.warn(strexp)

As you see where it existed before a digit followed by a letter now there is a digit followed by a script. The coincidences with the first parentheses of the pattern are at $1 and with the second at $2.

The first coincidence found is x0, then $1 contains x and $2 contains 0, replace it was found with -$2, that is, remove $1 and put a script and I will stay - in Place of x0. As the flag g has been used, this operation is carried out throughout the string.

a. Methods RegExp: Compile (cadpatr)

A search pattern can be constructed by means of a simple assignment or through the New Regexp builder and be used as such, but it can be improved quite the Search using this method that converts the pattern into an internal format to optimize its use. It uses as an argument a string that represents the regular expression that you want to compile:

let pattern = new RegExp();
pattern.compile('\\D-');
let find = pattern.exec('1234u90t-789');
logger.warn('Looking for ' + pattern.source);
logger.warn(find[0] + ' is in the position ' + find.index + ' de find.input');

In this example, any non-numeric followed by a script in the string "1234U90T-789" is sought. First, the pattern variable is declared and compiled with the \ d- pattern that indicates any non-numeric character followed by a hyphen. Finally, it shows the used pattern and the search results: match encountered, position and string explored.

b. Methods RegExp: Exec (cadexplor)

This method looks for the first match of the pattern with the content of the text string where it is sought, which is passed as an argument. If you can not find any match, but find a sequence of characters that suits the search pattern returns an array whose first element indicates the match found and the remaining results indicate the results according to the parentheses that appear in the regular expression.

In addition, this array has two properties :index, To indicate the position of the found subcade, and Input, which contains the string of characters that is being explored.

It also modifies the properties of a global regexp variable with data relating to the search. In the example that follows we are looking for any letter followed by a number and a script, the search pattern will be /[a..z]\ not-/i ,..z] represents all the letters of the alphabet, \D Represents any number and the i modifier is used so as not to differentiate lowercase uppercase.

```js pattern = /[a..z]D\d-/i; let find = new Array() find = pattern.exec('3c491a-9d1d6-91br'); if (find != null){ logger.warn('Concorded in: ' + find.index); logger.warn('Exploring:' + find.input); logger.warn('Founded.: ' + find[0]); } logger.warn('Rest ' + RegExp.rightContext);


### c. Methods RegExp: Test (cadexp)

This is the simplest method of regular expression object, it only checks if there is some coincidence in the string explored, past as argument, with the pattern of search. If there is such a coincidence, it returns a Boolean value True and otherwise returns FALSE.
It also affects the properties of the Global Regexp object.
```js
let pattern = new RegExp('Monday', 'gi');
let strexpl = 'the meeting is Monday or Tuesday.';
let ismonday = pattern.test(strexpl);
logger.warn('¿Is Monday? ' + ismonday);
logger.warn('Found in ' + RegExp.index);

In this simple example it is checked if the string scanned, strexpl, contains the word "Monday", without considering the box (uppercase or lowercase). The result saves it in the variable iMismanday

d. RegExp

It is a global variable used by JavaScript when performing operations where regular expressions intervene. Each time one of these operations are performed, the properties of this variable are modified. It is a variable that can be consulted but on which it can be modified directly, is read-only. It does not have any associated method and its properties always refer to a search operation, whether with the methods of a regular expression object or the String object.

Properties

$1..$9:

These indexes contain the parties grouped with parentheses in the search pattern.

input

string that has been explored.

lastmatch

Last match found.

multiline

Boolean variable indicating whether the scanned string includes line breaks.

lastParen

Last match encountered with a pattern in parentheses.

leftContext

The whole string to the coincidence found.

rightContext

The whole string from the coincidence until the end of the string.

These properties are only reading and are updated each time a pattern search is performed, whether with the methods of a regular expression or with String.

In the following example, these values can be observed after a search operation.

let pattern = /\D(\d)(\D)/g;
let findin = 'abde5fghj45oi';
let founded = patron.exec(findin);
logger.warn('$1: ' + RegExp.$1);
logger.warn('$2: ' + RegExp.$2);
logger.warn('input: ' + RegExp.input);
logger.warn('index: ' + RegExp.index);
logger.warn('lastIndex: ' + RegExp.lastIndex) ;
logger.warn('multiline: ' + RegExp.multiline);
logger.warn('lastMatch: ' + RegExp.lastMatch);
logger.warn('lastParen: ' + RegExp.lastParen);
logger.warn('leftContext: ' + RegExp.leftContext);
logger.warn('rightContext:' + RegExp.rightContext);

e. String object

The object string is used to manipulate character strings. In Javascript all text enclosed between quotes, double or simple, is interpreted as a string, so '45' is not number forty-five but the string formed by characters 4 and 5. The object string allows operations With strings like concatenate or divide strings, look for text, extract part of a text, etc. The operation of creating a variable of this type is carried out as usual with the operator new, being able to pass an argument to initialize The variable. By using a method or referring to a property we can use the name of the variable or a string constant thus the example:

let mytext = 'This is a string';
let pos = mytext.indexOf('a')

It can also be written in the following way:

let pos = 'This is a string'.indexOf('a');

Methods

anchor fromCharCode small
big indexOf split
blink italics strike
bold lastindexOf sub
charAt link substr
charCodeAt match substring
concat replace sup
fixed search toLowerCase
fontcolor slice toUpperCase
fontsize

Properties

length:

Returns the length of the string.

prototype:

Allows you to add methods and properties to the object

a. Methods of String: charAt(atrent)

This method applied to a string returns the character that is in the position given by the Atrent attribute, considering that the first character index to the Left of the string is 0 and the latter is a lower unit than length of the string.

If the value of the attribute is not valid (equal to or greater than the length of the string or negative) the method returns the value undefined For example, the following code returns the position of the third character of the string Name:

let name = 'abcdefghij';
let char3 = name.charAt(2);

Will return "c", which is the third character on the left (index equal to 2).

b. String methods: charAt(atrent)

This method applied to a string returns the unicode code of the character that is in the position given by the attribute atrent considering that the index of the First character to the left of the string is 0 and the latter is a lower unit than length of the string. If the value of the attribute is not valid (equal or greater than the length of the string or negative) the method returns the value nan. For example, the following code returns the unicode of the third character of the string Name: ```js let name = 'abcdefghij'; let car3 = name.charAt(2);

It will return 99, which is the letter of the letter 'c', the third character on the left (index equal to 2).

##### c. Methods of String: concat(atrstr)

This method applied to a string adds the string passing as attribute, **Atrstr**, that will be a variable or constant literal, any other type is converted to string. For example, the next Concatena 'good' code and 'morning':
```js
let greeting = 'Good ';
let hello = greeting.concat('morning');

The variable hello will contain "Good Morning", it is the same as if it had been written:

let hello = greetings + 'morning'
d. Methods of String: fromCharCode( cod1, cod2, ... )

This is a global method of the String object that creates a string from the Unicode codes that are passed as parameters. For instance:

let str = String.fromCharCode(65, 66, 67);

The stirng variable will contain 'ABC', which are the characters with codes 65, 66 and 67.

e. Methods of String: indexOf( atrcad, from)

This method returns the first position within the String object where the last sub-cadena begins as an argument at Atrcad. It supports a second optional argument that indicates from which position you must perform the search, if it is omitted, start searching for the first character on the left.

Values of the second negative argument or greater than the length of the chain are considered 0. If the substring is not the returned value is -1. For instance:

let str = 'my.mail@mail.com';
let atsign = str.indexOf('@');
let dot = str.indexOf('.',4);

This example returns in atsign position 7 while dot contains 11 because the search was made from the position where the character is at and finds the second point. Remember that the positions in the chains are counted from 0.

f. Methods of String: lastIndexOf(atrcad, from)

This method returns the first position within the String object where the last sub-cadena begins as an argument at Atrcad, but performing the right search to left. Supports a second optional argument that indicates from which position you must perform the search, if it is omitted start searching for the first character on the right, negative or greater values that the length of the string are considered 0. If the subcadena is not the returned value is -1. For instance:

let str = 'my.mail@mail.com';
let atsign = str.lastIndexOf('@');
let point = str.lastIndexOf('.',atsign);

This example returns in atsign position 7 while point contains the 2 because the search was made from the position where the character is at the beginning of the string finding the first point. Remember that the positions in the strings are counted from 0.

g. Methods of String: match( expreg )

This is one of the most powerful methods to search for substrings and perform substitutions within text strings. It allows to use search patterns built with wildcards and text, which are called regular expressions. This method uses as argument a regular expression and is looking at the object some subcade that agrees with that expression. This subcade is returned it in an array. If you can not find none returns null. It also updates the value of a global variable regexp that stores on your properties diverse information about the search performed. By example:

let phrase = 'I am looking for words with less than five letters';
let result = phrase.match(/\b\w{1,4}\b/g);
logger.warn('Found: ' + result);
logger.warn('In the phrase: ' + RegExp.input);

If you try the example you will get the following list:

Found: I,am,for,with,less,than,five
In the phrase: I am looking for words with less than five letters

The search pattern is enclosed between two bars /, and looks for alphanumeric characters (\w) between word limits (\b) also does a global search (indicated by g Out of the bars).

h. Methods of String: replace ( expreg, new )

A turns with regular, difficult but powerful expressions. With this method all the strings that match the Expreg of the first argument are replaced by the string specified in the second argument, new, which can contain elements of the pattern using the $1 to $9 symbols.

The returned result is the string with the substitutions made. For example we are going to change word by phrase in the phrase "each word said is a false word":

let line = 'Each word said is a false word';
line = line.replace(/word/g, 'phrase');
logger.warn(line);

If you try the example you will get the following:

Each phrase said is a false phrase

On this occasion, a pattern has been used with the g modifier for what all matches change, if only the first is changed.

i. Methods of String: search ( expreg )

It is a method similar to the Match method but faster. This method performs a search in the string and returns the index where the first agreement is produced with the O -1 pattern if there is no. For example, we look for the strings 'Monday' or 'Tuesday' in the quotation phrase, the letter i of the pattern indicates that you should ignore the uppercase or lowercase type in the search:

let pattern = /Monday|Tuesday/i;
let appointment = 'The meeting will be on monday and wednesday';
logger.warn(appointment.search(pattern));

If you try the example you will get a 23, the position of the word 'monday'.

j. Methods of String: slice ( Start, last )

This method returns the string portion between the positions given by the start and last arguments, or the end of the string if this second argument is omitted.

If last is negative, it is interpreted as the number of positions counted from the end of the string. If the arguments are not whole numbers, for example strings, they become entire numbers as the method would do Number.parseInt().

let fhrase = 'Author: Lewis Jons';
let name = frase.slice(8);

The variable name will contain "Lewis Jons". In another example we use a second argument :

let fhrase = 'Author: Lewis Jons';
let name = frase.slice(8, -5);

name willl contain "Lewis", that is, from position 8 to 5 positions before the end.

k.Methods of String: split (separator)

Returns an array containing the portions on which the string is separated by the separator indicated by the argument separator, which will be a regular expression or a literal chain. If this separator is an empty string the text is broken down into all its characters. If the separator is omitted the result is an array of an element with the full string:

let line = 'Title: The doorman';
let list = line.split(/:\s*/);

The variable list is an array with two elemtnts "Title" and "the doorman". We could also have written it as:

let line = 'Title: The doorman';
list = line.split(':');
logger.warn(list);

In this case the first list element is "title" and the second " The doorman" with a space ahead.

Finally, if the separator is an empty string:

let line = 'Title: The doorman';
list = line.split('');
logger.warn(list);

the list variable will contain T, í, t, l, e,:, , T, h, e, , d, o, o, r, m, a, n.

l. Methods of String: substr(Start, Long)

Returns an extracted subcade of the String object starting with the given position by the first argument, Start, and with a number of characters given by the second argument, Long. If this last argument is omitted the extracted subcadena is from Start until the end of the string.

let line = 'My page is ideal';
let list = line.substr(3);

The list variable will contain "page is ideal".

let line = 'My page is ideal';
let list = line.substr(3, 4);

Now the variable list will contain "page".

m. Methods of String: substring(ind1,ind2)

Returns a subcade of the String object that begins in the position given by the lower of the arguments and ends at the position given by the other argument. If this last argument is omitted the extracted subcade is from the position indicated by the only argument until the end of the string. If the arguments are literal they become integers as a parseint().

let line = 'My page is ideal';
let list = line.substr(3);

The list variable will contain "page is ideal".

let linea = 'My page is ideal';
let lista = linea.substr(3, 7);

Now the variable list will contain "page", as in:

n. Métodos de String: toLowerCase()

Returns a string equal to the original but with all the characters in lowercase. It does not affect how is logical to non-alphabetic characters, that is, numbers, accentuated letters and special characters such as ñ:

let line = 'Today is Sunday';
line = line.toLowerCasesubstr();

The variable list will contain "today is sunday". 

o. Methods of String: toUpperCase()

Returns a string equal to the original but with all the characters in capital letters. It does not affect how logical non-alphabetic characters, that is, numbers, accentuated letters and special characters like ñ. It is very useful when comparing strings to ensure that two strings do not differ only because some character is uppercase or lowercase.

let line = 'Today is Sunday';
line = line.toUpperCase();

The variable list will contain "TODAY IS SUNDAY".

H. Date object

The Date object contains a value that represents date and time of a given moment. To create an instance of this object we use any of the following syntax:

let vDate = new Date()
let vDate = new date(number)
let vDate = new date(string)
let vDate = new date(year, month, day[, hour[, minutes[, second[,millisecond]]]])

The arguments locked between brackets are optional. In the first form the variable vDate will contain the current day date.

The second option stored the date given by the argument as the number of milliseconds elapsed since midnight of January 1, 1970.

The third type is used when the date is passed in the form of a string.

Finally, the date can be created by as argument the year numbers, month, day, hour and optionally, hour, minute, second and millisecond.

The years after 1970 can be written with two digits, but it is advisable to always use four digits for that of the 2000 effects.

let today = new date() /*date of the day in today */
let event = new Date('November 10 2020');
let other = new Date('10 Nov 2020');
let other = new Date('10/02/2021'); //Oct, 2, 2021
let instant = new Date(2021, 11, 10, 20, 00);

These are three possible ways to declare date objects. The last two store the same day, but in the last one it is also saved the time.

Where string are used to indicate a date we can add at the end the GMT (or UTC) acronym to indicate that the time refers to Meridian Time Greenwich, if not taken as a local time, that is, according to the time zone configured in the adquio Where the script is executed.

Methods

getDate parse
getDay setDate
getFullYear setFullYear
getHours SetHours
getMilliseconds setMilliseconds
getMinutes setMinutes
getMonth setMonth
getSeconds setSeconds
getTime setTime
getTimezoneOffset setYear
getYear toGMT
Object.toString toLocaleString
Object.valueOf toUTCString**
a. Methods of Date: getDate()

It returns us on the day of the date object to which it is applied. This method of course controls the number of days of each month and contemplates the case of leap years, including the exception of 2000. In the following example it is on the screen today is day 2, assuming that the date of the system is 2-10- 2020. First we create the instantiated date variable as an object date() for then directly write the value of getdate() applied to date

let vDate = new Date();
logger.warn('Today is day: ' + fecha.getDate());
b. Methods of Date: getDay()

It returns us on the day of the week of the date onject, that is applied numerically with a figure between 0 for Sunday and 6 for Saturday.

In the following example, Today is 2, assuming that the date of the system is 2-October-2021, I mean, Friday. First we create the variable instantiated date as an object date() for then to write directly the value of Getday() applied to date

let vDate = new Date();
logger.warn('Today is ' + vDate.getDay());

If we take hands out of an array we can improve a little this example by presenting the name of the day of the week:

let vDate = new Date();
let WeekDay = new Array('sunday', 'monday', 'tuesday', 'wednesday', 'thrusday', 'friday','saturday');
let day = vDate.getDay();
logger.warn('Today is ' + WeekDay[day]);

Now the most friendly phrase would be obtained Today is Friday.

c. Methods of Date: getFullYear()

It returns us the corresponding year of the date object in complete format is to say including the century. So if the date contains 2-October-2021, this function will give us 2021. For example, we create the variable date instantiated as an object Date() for below, the value of getfululyear() is directly presented Applied to date, that is, 2021.

let vDate = new Date();
logger.warn('The current year is ' + vDate.getFullYear());

This method avoids the 2000 effect by presenting the years always with four digits.

d. Methods of Date: getHours()

Return the Hours section in 0-24 format stored in the part delivered at the date of the date object to which it is applied. So if the date contains 12:40:00, this function will give us 12, but if it contains 5:40:00 it will give us 17. Likewise the method interprets the AM / PM modifiers but always returns the time in 24 hour format. For example, we create the variable date instantiated as an object Date(), if it is 17:30:10 the value of gethoursr() will present 17.

let vDate = new Date();
logger.warn('It´s ' + fecha.getHours() + ' hours.');

You can try that it happens with other values without the need to change the date and time of adquio as follows:

let vDate = new Date('10-02-2021 08:20:00 pm');
logger.warn('It´s ' + fecha.getHours() + ' hours.');

This case will present on the log It´s 20 hours

e. Methods of Date: getMilliseconds()

It returns the milliseconds of the section dedicated to the time stored in the date object that is applied. So if the date contains on your part of time 12:40:08:640, this function will give us 640. For example, we create the variable date instantiated as an object Date(), if it is 17:30:08:550 The value of getmilliseconds() will present 550.

let vDate = new Date();
logger.warn('It´s ' + vDate.getHours());
logger.warn(':' + vDate.getMinutes());
logger.warn(':' + vDate.getSeconds());
logger.warn(':' + vDate.getMilliseconds());
f. Methods of Date: getMinutes()

We returned the minutes from the section dedicated to the time stored in the date object to which it is applied. So if the date contains at your time of time 12:40:08, this function will give us 40. For example, we create the variable date instantiated as an object Date(), if it is 17:30:08 the value of getminutes() will present 30.

let vDate = new Date();
logger.warn('It´s ' + vDate.getHours());
logger.warn(':' + vDate.getMinutes());
logger.warn(':' + vDate.getSeconds()); ;

If we want it to be more presentable, we can complete with zeros on the left when the number (hours, minutes or seconds) is less than 10. This is as easy as it is seen in the example:

let vDate = new Date();
let hours = vDate.getHours();
let mins = vDate.getMinutes();
let secs = vDate.getSeconds();
hours = (hours < 10) ? ('0' + hours) : hours;
mins = (mins < 10) ? ('0' + mins) : mins;
secs = (secs < 10) ? ('0' + secs) : secs;
logger.warn('It´s ' + hours);
logger.warn(':' + mins);
logger.warn(':' + secs);
g. Methods of Date: getMonth()

It returns us numerically the month corresponding to the date object to which it is applied. So for the date corresponding to 10/Oct/2021, this function will give us 10, the October order number. For example, we create the date variable instantiated as an object Date():

let vDate = new Date();
logger.warn('This month is the ' + vDate.getMonth());

If we want the name of the month instead of the number we must first create a array of twelve elements and fill them with the names of the months, then we use the result of getmonth() as an index to that array :

let array = new months();
let vDate = new Date();
let month = vDate.getMonth();
months[1] = 'January';
months[2] = 'February';
months[3] = 'March';
months[4] = 'April';
... ...
logger.warn('Current month: ' + months[month]);
h. Methods of Date: getSeconds()

It returns us the seconds of the section dedicated to the time stored in the date object that is applied. So if the date contains at your time of time 12:40:08, this function will give us 8. For example we create the variable date instantiated as an object Date(), if it is 17:30:08 the value of getseconds() will present 8:

let vDate = new Date();
logger.warn('It`´s ' + vDate.getHours());
logger.warn(':' + vDate.getMinutes());
logger.warn(':' + vDate.getSeconds()); ;

If we want you to be more presentable, we can complete with zeros on the left when the number (hours, minutes or seconds) is less than 10. This is as easy as it is seen in the example:

let vDate = new Date();
let hours = vDate.getHours();
let mins = vDate.getMinutes();
let secs = vDate.getSeconds();
hours = (hours < 10) ? ('0' + hours) : hours;
mins = (mins < 10) ? ('0' + mins) : mins;
secs = (secs < 10) ? ('0' + secs) : secs;
logger.warn('It´s ' + hours);
logger.warn(':' + mins);
logger.warn(':' + secs);
i. Methods of Date: getTime()

We returned the amount of milliseconds since January 1, 1970 to the time stored in the date it is applied. In the example that continues we create an object Date with the current date, then we write the number of milliseconds given by this function, you will see that this number is usually very large, this function can really be useful to calculate the elapsed time Between two instants, for example in a puzzle it could be useful to calculate the time the player uses to solve the puzzle, subtracting the getttime() obtained at the end of the game of getttime() obtained at the beginning.

let now = new Date();
logger.warn(now.getTime());
j. Methods of Date: getTimezoneOffset()

This function gives us the time difference in minutes of adquio with respect to the Greenwich meridian. The value depends therefore of the zone or time zone for which it is configured adquio, being negative or positive as it is in the eastern or western zone.

The example showing the use of the function defines the variable now with the current date and returns in minutes the time difference with the GMT, the result depends on your adquio.

let now = new Date();
logger.warn(now.getTimezoneOffset());
k. Methods of Date: getYear()

It returns numerally the year corresponding to the date object to which it is applied. So for the date corresponding to 10/Oct/2021, this function will give us 2021. For example we create the variable date instantiated as an object Date(), and then we extract the year:

let vDate = new Date();
logger.warn('This year is the ' + vDate.getYear());
l. Métodos de Date: Object.toString()
m. Métodos de Date: Object.valueOf()

The cases object.Tostring, and object.valueof, were already explained in section E) object object.

n. Methods of Date: parse(fecha)

We returned the amount of milliseconds since January 1, 1970 00:00:00 until the last hour in the argument date as a string of characters. This method is a global method of the object and therefore it is not necessary to create an object date to use it, as we see in this example.

let elapsed = date.parse('1/1/2021 00:00:00');
logger.warn(elapsed);
o. Methods of Date: setDate(day of the month)

It allows us to change the day's day of the date object to which it is applied to put the value that has happened in the argument day of the month. This method controls of course the number of days of each month and contemplates the case of leap years, including the exception of 2000, so that if we go as argument 31 and the month is 30 days the function corrects the full date passing it up to date 1 of the following month. We see this in the example below: We create a variable as an object date with the last September day (30-day month) and we try to put on the day to 31, then we check the stored date:

let vDate = new Date('1 Sep 2021');
fecha.setDate(31);
logger.warn('Today is day: ' + fecha.toString());

As you will see if you test the example the date is corrected and goes on to October 1.

p. Methods ofDate: setFullYear()

It allows us to change the year of the date object due to the value last as an argument, a number interpreted as a full year, that is, that to put the year 2020, 2020 should be passed, not on 20. The example puts precisely this value in the year field of the variable date.

let vDate = new Date();
fecha.setFullYear(2021)
logger.warn(vDate.toString());
q. Methods of Date: setHours()

It allows us to modify the time stored in the date object that is applied and putting the one that is passed as an argument. Logically, this argument will be between 0 and 24, although if a value is used outside this range, the date is corrected accordingly. For example, if we try to put the time on 30 the date is ahead 24 hours and set at 6 hours, changing also the day. Likewise, if a negative number is used in the argument is taken as hours before the last half of the same day. Observe all this in the example, where at the end of each action the full date is presented in the form of a string:

let vDate = new Date('10 Sep 2021 00:00:00');
vDate.setHours(20);
logger.warn('At 20: ' + vDate.toString());
vDate.setHours(30);
logger.warn('At 30.: ' + vDate.toString());
vDate.setHours(-2);
logger.warn('At -2: ' + vDate.toString());
r. Methods of Date: setMilliseconds()

It allows us to modify the number of milliseconds of the time stored in the date object to which it is applied, putting the milliseconds to the last value as an argument. Usually the argument will be between 0 and 1000.

let vDate = new Date('10 Sep 2000 00:00:00');
vDate.setMilliSeconds(900);
logger.warn(vDate.toString());
s. Methods of Date: setMinutes(minact)

It allows us to adjust the minutes of the section dedicated to the time stored in the date object that is applied. The new value for the minutes is passed as an argument, which will usually be between 0 and 59, although a value outside this range does not give an error but adjusts the rest of the time. So 68 in the argument advances the clock one hour puts the minutes at 8, while a -4 puts the minutes at 56 (60 minus 4). You can see what happens in this example:

let vDate = new Date('10 Sep 2020 00:00:00');
vDate.setMinutes(20);
logger.warn('Minact 20: ' + vDate.toString());
vDate.setMinutes(68);
logger.warn('Minact 68: ' + vDate.toString());
vDate.setMinutes(-4);
logger.warn('Minact -4: ' + vDate.toString());

As you see if necessary, the time is adjusted when the number of minutes exceeds the value 59.

t. Methods of Date: setMonth()

This function is used to modify the date of the date object to which it is applied. The new value is passed as a number in the argument. The value must be as is numeric or convertible to numerical and between 0 (January) and 11 (December). If the value is outside the range, the excess is taken on 11 and the date is properly corrected, and if it is negative it is taken as number of months before January (-1 it would be December, -2 it would be November, etc.). The example is very simple, in this case the month of September is changed by March

let vDate = new Date('10 Sep 2021 00:00:00');
vDate.setMonth(2);
logger.warn('Current month : ' + vDate.toString());
u. Methods of Date: setSeconds()

It allows us to modify the number of seconds of the time stored in the date object that is applied, putting the second to the value last as argument.

Usually the argument will be between 0 and 60.

let vDate = new Date('10 Sep 2021 00:00:00');
vDate.setSeconds(90);
logger.warn(vDate.toString());
v. Methods of Date: setTime()

We returned the amount of milliseconds since January 1, 1970 to the time stored in the date it is applied.

In the example that continues we create an object date with the current date, then we write the number of milliseconds given by this function, you will see that this number is usually very large, this function can really be useful to calculate the elapsed time Between two instants, for example in a puzzle it could be useful to calculate the time the player employs to resolve the puzzle, subtracting the settime() obtained at the end of the set settime() obtained at the beginning.

let now = new Date();
logger.warn(now.setTime());
x. Date methods: setYear()

It allows us to change the date of the date object for the value last as argument, a number interpreted as a full year. The example sets precisely this value in the Year field of the variable Date.

let vDate = new Date();
vDate.setFullYear(2021)
logger.warn(vDate.toString());
y. Methods of Date: toLocaleString()

This function is used to transform the date object to which it is applied to a character string according to the standard UTC (Universal Time Coordinates), Current Denomination of the GMT (Greenwich Meridian Time). The time is adjusted according to the configuration of adquio. In the example that the returned string follows will be "Mon, 10 Apr 2020 02:00:00 UTC":

let vDate = new Date('10 Apr 2000 02:00:00');
logger.warn(vDate.toUTCString());

As you see there is a difference in the stored time and returned by the function, this is because the string returned is the time corresponding to Greenwich, not the adquio local.

z. Methods of Date: toUTCString(date)

Returns us the amount of milliseconds since January 1, 1970 00:00:00 Until last hour in the argument Date. This argument is passed as a series of numbers separated by commas in order: year, month, day, and optionally: Time, Minute, Seconds. This method is a global method of the object and therefore is not necessary to create an object Date to use it, as we see in this example that it takes as a current date on November 1, 2000 at 00:00:00.

let transc = Date.UTC(2000, 10, 1);
logger.warn(transc);

I. Math Object

It is the object that JavaScript uses to provide the language of mathematical functions advanced and predefined constants, such as pi number.

Methods

abs : Absolute value cos : cosine pow : Power of
acos :Cosine arch exp : Exponential random : Random number
asin : Bow sine floor : Lower rounding round : Round out
atan : Tangent arch log : Natural logarithm sin : sin
atan2 :Tangent arch max : maximum sqrt : Square root
ceil : Superior rounding min : Minimum Tan : Tangent

Properties

They are the usual constants as the number E, pi and some other usual values in mathematical calculations.

E Constant euler the basis for natural logarithms LN10 Natural logarithm of 10 LOG10E Logarithm on base 10 of e SQRT1_2 Square root of 0.5 that is the reverse root of 2
LN2 Natural logarithm of 2 LOG2E Logarithm on base 2 of E PI The know number pi SQRT2 Square root of 2
a. Math Methods: abs(exprnum)

Returns the absolute value, that is, without sign, of the argument. If the argument was not whole will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let numabs = Math.abs( - 45)

The variable numabs will contain the value 45.

b. Math Methods: acos(exprnum)

It is a trigonometric function that serves to calculate the angle whose cosine is the value given by the argument, the Arccos ().

This argument must be a numerical or transformable expression in numerical, comprised between -1 and + 1 and the returned angle is given in radians.

let arco = Math.acos( 1)

The variable arc will contain the value 0.

Remember The radian is a unit of measurement of arcs such that 2*pi radians equals 360º.

c. Math Methods: asin(exprnum)

It is a trigonometric function that serves to calculate the angle whose breast is the value given by the argument, that is, the so-called Arcosen. This argument must be a numerical expression, or transformable in numerical, comprised between -1 and +1 and the returned angle is given in radians.

let vArc = Math.asin( 1 )

The variable vArc will contain the arc whose breast is 1, that is, 1.57 or what is the same PI/2 radians.

Remember Radián is a unit of measurement of arches such that 2*pi radians equals to 360º.

d. Math Methods: atan(exprnum)

It is a trigonometric function that serves to calculate the angle whose tangent is the value given by the argument, that is, the ARCTG (). This argument must be a numerical or transformable expression in numerical, without limits, and the returned angle is given in radians.

let VAarc = Math.atan( 1 )

The variable vArc will contain the arc whose tangent is 1, that is, 0.7853981633974483 or what is the same PI/4 radians (45º).

Remember Radián is a unit of measurement of arcs such that 2*pi radians equals 360º.

e. Math Methods: atan2(coorX, coorY)

It is a trigonometric function that serves to calculate the angle whose tangent is the quotient of its arguments, in other words it returns the angle from the origin of coordinates to a point whose coordinates are the arguments of the function. The arguments must be numerical or transformable in numerical, and the returned angle is given in radians.

let argum = Math.atan2(10, 4);

The variable argum will contain the arch whose tangent is 10/4.

Remember Radián is a unit of measurement of arcs such that 2*pi radians equals 360º.

It is a useful function to work with complex numbers because it really calculates the argument of a complex where coord is the real part and coox is the imaginary.

f. Math Methods: ceil(exprnum)

Returns the value of the rounded argument by excess, ie the smallest whole number or equal to the argument. If the non-numeric argument will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let redexceso = Math.ceil( 4.25)

The variable redexceso will contain the value 5.

g. Math Methods: cos(exprnum)

It is a trigonometric function that serves to calculate the cosine of the last angle as an argument in radians. This argument must be a numeric or transformable expression in numerical.

let cosine = Math.cos( Math.PI/2)

The variable cosine will contain the value 0, which is the cosine of PI/2 radians (90º).

h. Math Methods: exp(exprnum)

Returns the value of number E (Euler constant, approximately 2,178) elevated to the exponent given by the argument. If the argument was not whole will be converted to numerical following the rules of functions parseint() or parsefloat(). Your syntax is as simple as the example:

let e4 = Math.exp(4)

The variable e4 will contain the value e^4. The number e is the basis of neperian logarithms so this function serves to calculate antilogaritms.

i. Math Methods: floor(exprnum)

Returns the value of the rounded argument by default, that is, the greatest whole number less than or equal to the argument. If the non-numeric argument will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let redexceso = Math.floor( 4.75)

The variable redexceso will contain the value 4.

j. Math Methods: log(exprnum)

Returns the natural or neperian logarithm, that is, based on the number e, of the argument. If the non-numeric argument will be converted to numerical following the rules of the function parseint() or parsefloat(). If the argument was a negative value this function returns NaN. Your syntax is as simple as the example:

let logarithm = Math.log( 1000)

The variable logarithm will contain the value 6.907755278982137.

k. Math Methods: max(num1, num2)

Returns the greatest of the two numbers or last numerical expressions as arguments. If any of the non-numeric arguments will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let greater = Math.wax( 12, 5)

The variable greater will contain the value 12.

l. Math Methods: min(num1, num2)

Returns the smallest of the two numbers or last numerical expressions as arguments. If any of the non-numeric arguments will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let minor = Math.min( 12, 5)

the variable minor will contain the value 5.

m. Math Methods: pow(base, exp)

Calculate the power of a number, given by the argument base, raised to the exponent given by the argument exp.

If any of the non-numeric arguments will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let Power = Math.pow( 2, 4)

The variable Power will contain the value 16.

n. Math Methods: random()

Calculate a random number, really pseudo-random, comprised between 0 and 1 inclusive. Each time the JavaScript interpreter is loaded, a base seed is generated for the calculation. It does not take arguments and their syntax is as simple as the example:

let vRandom = Math.random()*10

The variable vRandom will contain a random number between 0 and 10.

o. Math Methods: round(exprnum)

Returns the entire value closest to last number as an argument, that is, rounded. If the decimal part of the argument is 0.5 or greater returns the first whole above the argument (round rounding) otherwise returns the entire entire to the argument (default rounding). If the argument was not whole will be converted to numerical following the rules of the function parseint() or parsefloat(). Your syntax is as simple as the example:

let integer1 = Math.random(4.25)
let integer2 = Math.random(4.65)

The variable integer1 will contain the value 4 while integer2 that will contain 5.

p. Math Methods: sin(exprnum)

It is a trigonometric function that serves to calculate the breast of the last angle as an argument in radians. This argument must be a numeric or transformable expression in numerical.

let vSin = Math.sin( Math.PI/2)

The variable vSin will contain the value 1, which is the sinus of 2 radians (90º).

q. Math Methods: sqrt(exprnum)

Returns the square root of the last value as an argument. If the argument was not whole will be converted to numerical following the rules of the function parseint() or parsefloat(). If the argument was negative or any other non-numeric value will return NaN. Your syntax is as simple as the example:

let Root = Math.sqrt( 49)

The variable root will contain the value 7.

r. Math Methods: tan(exprnum)

It is a trigonometric function that serves to calculate the tangent of the last angle as an argument in radians. This argument must be a numeric or transformable expression in numerical.

let vTangent = Math.tan( Math.PI/4)

The variable vTangent will contain the value 1, which is the PI/4 radian tangent (45º).