Where the data js object is formed. How can I access and process nested objects, arrays or JSON? JavaScript Location, Navigator, Screen objects

The data method in jQuery gives us the ability to bind arbitrary data to any document or javaScript object, which makes your code more concise and readable. Since jQuery 1.4.3 it is possible to use this method for javaScript objects, as well as track changes in this data.

The basics

To begin with, you can call the data method on a jQuery object, and also use the $ .data () function directly.

// Using the method: $ ("# myDiv"). Data ("key", "arbitrary value"); // Using the function directly: $ .data ($ ("# myDiv"). Get (0), "key", "arbitrary value");

The data function is a low-level implementation that is actually used when the method is called. The jQuery object method is much more convenient, it also allows itself to be included as a chain of calls.

Also, note that you need to pass a DOM element, not a jQuery object, as the first parameter to the $ .data function.

An object method requires two parameters - a key and a value. The key is a string constant, and the value is any data structure, including functions, arrays and objects. There is an alternative syntax where you can pass an object as one parameter:

// You can pass an object: $ ("# myDiv"). Data (("name": "Stevie", "age": 21)); // Same thing: $ ("# myDiv"). Data ("name", "Stevie"). Data ("age", 21);

Now, if you need to get the saved data, you can call the data function, passing it the key as a parameter:

Var theValue = $ ("# myDiv"). Data ("age"); // 21

Access to this data is open anywhere in the script. You will receive the stored data as long as there is an element retrieved by the given selector.

Var theValue = $ ("div: first"). Data ("name"); // Stevie $ ("div: first"). Click (function () (alert ($ (this) .data ("age"); // 21));

JQuery 1.4.3 also provides HTML5 data stored in attributes. This means that if you have an element declared like this:

In this case, you can get the data from the data-internal-id attribute by calling the $ ("# img1"). Data ("internal-id") method, which is undoubtedly useful for AJAX requests.

Using the data method for javaScript objects

You might be surprised, but the data method can also be used for regular javaScript objects. This functionality was officially introduced in jQuery 1.4.3.

Var myObj = (); $ (myObj) .data ("city", "Springfield");

The above example actually creates a city property for the given object. Why not just write myObj.city = "Springfield" then? The difference is that the data method adds several useful events to the object to make it easier to work with this object. For example:

Var progressBar = (); $ (progressBar) .bind ("setData", function (e, key, value) (switch (key) (case "percent": $ ("# progress"). width (value + "%"); $ ("# percentText "). text (value +"% "); break; case" color ": $ (" # progress "). css (" color ", value); break; case" enabled ": $ (" # progress ") .toggleClass ("active", value); break;))); $ (progressBar) .data ("enabled", true) .data ("percent", 21) .data ("color", "green"); console.log (progressBar.enabled);

In the above example, we use the data method to create the simplest API with which we can update an element.

There are two more events that can be used for a javaScript object:

  • getData - fires before reading data. You can use it to preprocess the received data. For example, to recalculate a value.
  • changeData - fires when data is set or changed. This event is used by the jQuery datalink plugin. It allows you to bind form data to a javaScript object and treat form fields as object properties.

Behind the scenes

jQuery creates an empty object (for the curious, it's called $ .cache), which is the store of all the values ​​that you store using the data method. Each element from the DOM that is used with the data method is assigned a unique identifier, which is then the key to access the data in the $ .cache object.

jQuery stores not only user data in this cache, it also stores internal data, event handlers that you hang using the live (), bind () and delegate () functions. Using a central repository makes jQuery more robust.

Conclusion

The data method is just one of the many jQuery features that make life easier for web developers. When combined with the library's other capabilities, it complements a solid foundation that we can rely on.

This lesson will cover Javascript objects. We will talk about custom objects: creating an object in javaScript, working with object properties and methods, as well as javascript prototypes. Working with objects is summarized Location, Navigator, Screen


The task of the site site is to provide users with practical skills in working with the language. Laboratory works on javaScript, presented as their complexity increases and supported by visual solved examples, will allow you to easily perceive the studied material and learn how to independently create "live", dynamic web pages.


There are several kinds of objects in javaScript:

  • built-in objects
  • browser objects
  • objects that the programmer creates on his own (custom)

Built-in objects are predefined objects, ... Most of which have already been covered in previous lessons.

Browser objects in javaScript will be discussed in further lessons.

Now is the time to get to know custom objects in javaScript.

  • Object
  • Number (number processing)
  • String (string processing)
  • Array (arrays)
  • Math (mathematical formulas, functions and constants)
  • Date (working with dates and times)
  • RegExp
  • Global (its properties are Infinity, NaN, undefined)
  • Function

JavaScript object creation

There are 2 ways to create objects:

  1. Using an object initializer (or creating collection objects)
  2. Using Object Constructor ()
  1. Creating collection objects
  2. var object_name = new Object (); object_name.property = value; // dot notation object_name ["property"] = value; // bracket notation

    Important: It is worth noting that you cannot use a digit as a value: myObg.rost = 2 // DO NOT! myObg.rost = "2" // you can

    Example: Create myBrowser object with name properties (value ) and version (value " 9.0 »)


    ✍ Solution 1:

    var myBrowser = new Object (); myBrowser.name = "Microsoft Internet Explorer"; myBrowser [" version "] =" 9.0 ";

Example: Create two collection objects (car and moto) with color and brand properties. Print property value color at the object car and properties brand at the object moto.


✍ Solution:
    var car = new Object (); car.color = "White"; car.maxSpeed ​​= 220; car.brand = "Nissan"; document.write ("Car has color:" + car.color); var moto = (color: "Blue", horsePower: 130, brand: "Yamaha"); document.write ( "Have a motorcycle manufacturer:"+ moto.brand);

    var car = new Object (); car.color = "White"; car.maxSpeed ​​= 220; car.brand = "Nissan"; document.write ("Car has color:" + car.color); var moto = (color: "Blue", horsePower: 130, brand: "Yamaha"); document.write ("The motorcycle has a manufacturer:" + moto.brand);

Loop "for each" for in when working with objects in javascript

Quite a bit about this design has already been said in.
The for in loop in javascript is for looping through arrays, collections, and objects.

Let's look at an example of using for in:

1 2 3 4 5 6 7 8 var myBrowser = new Object (); myBrowser.name = "Microsoft Internet Explorer"; myBrowser ["version"] = "9.0"; for (var a in myBrowser) (alert (a); // Loops through the properties of the myBrowser object. Will return name, version alert (myBrowser [a]); // Will return property values }

var myBrowser = new Object (); myBrowser.name = "Microsoft Internet Explorer"; myBrowser ["version"] = "9.0"; for (var a in myBrowser) (alert (a); // Loops through the properties of the myBrowser object. Returns name, version alert (myBrowser [a]); // Returns property values)

  • Creating Constructor Classes
  • The creation of constructor classes is carried out in two stages:

    1. first, the class is created using the constructor;
    2. then created new object based on the constructor.

    Creating an object class using a constructor (creating constructor classes):

    function Object_class_name (sv-vo1, sv-vo2) (this.cv-vo1 = value; this.cv-vo2 = value;)

    Creating a new object based on the constructor for the object class:

    var object_name = new class_name ("sv-va1 value", "sv-va2 value");

    var object_name = new class_name (); object_name.cv-va1 = "value_cv-va1"; object_name.cv-va2 = "value_cv-va2";

    It is customary to write the name of the constructor class with a capital letter!


    Let's consider an example:

    Example: Create a constructor for a class of objects and create an object based on this class: create an object myBrowser with properties name (value "Microsoft Internet Explorer") and version (value " 9.0 »)

    Open solution

    1 2 3 4 5 6 7 8 function Browser (name, version) (this .name = name; this .version = version;) var myBrowser = new Browser ("Microsoft Internet Explorer", "9.0"); alert (myBrowser.name); alert (myBrowser.version);

    function Browser (name, version) (this.name = name; this.version = version;) var myBrowser = new Browser ("Microsoft Internet Explorer", "9.0"); alert (myBrowser.name); alert (myBrowser.version);

    So, let's compare again with the first way to create objects:

    // collection object var myBrowser = (name: "Microsoft Internet Explorer", version: "7.0"); alert (myBrowser.name); alert (myBrowser.version); // next line unacceptable! var myBrowser1 = new myBrowser ("MozillaFirefox", "3.5"); // WRONG! !!

    Important: In the case of creating a collection object, you cannot create an instance of the class, since it is not a class


    Job js 6_1. Create an Employee object that contains information about employees of a certain company, such as Name, Department, Phone, Salary (use the constructor function and the this keyword). Instantiate an object

    Accessing object properties in javaScript

    Object_name. property_name

    1 2 agent007.Name = "Bond"; alert (agent007.Name);

    agent007.Name = "Bond"; alert (agent007.Name);

    What is the default property

    The constructor function allows you to endow an object with default properties. Each instance of an object will have these properties.

    1 2 3 4 5 6 7 8 9 10 function Student (name, phone) (this .name = name; this .phone = "22-22-22"; // default property!) var ivanov = new Student ("Ivan", "33-33-33"); alert (ivanov.name); // will display "Ivan" alert (ivanov.phone); // will return "22-22-22" ivanov.phone = "33-33-33"; // change the default property alert (ivanov.phone); // will return "33-33-33"

    function Student (name, phone) (this.name = name; this.phone = "22-22-22"; // default property!) var ivanov = new Student ("Ivan", "33-33-33" ); alert (ivanov.name); // will display "Ivan" alert (ivanov.phone); // will return "22-22-22" ivanov.phone = "33-33-33"; // change the default property alert (ivanov.phone); // will return "33-33-33"

    Adding Properties to an Object Class

    Property value can be added for:

    • a specific instance of an object;
    • whole class of objects

    Adding properties to a specific(instance) object:

    object_name. property_name = value

    ivanov.biology = "excellent";

    Important: The example sets the property to a specific object, not to a class of objects!

    Adding properties to the class objects:

    class_name.prototype. property_name = value

    Student.prototype.biology = "excellent";

    Important: The example sets the (default) property for the object class! This is done with prototype; prototype- the object that defines the structure

    1 2 Student.prototype .email = " [email protected]"; alert (ivanov.email); // will return " [email protected]"

    Student.prototype.email = " [email protected]"; alert (ivanov.email); // will display" [email protected]"

    Example: An example of displaying all properties of an object with values

    1 2 3 4 5 6 7 8 9 var summerTour = (turkey: 2000, spain: 3000, egypt: 1000); var option; for (option in summerTour) (document.write (option + ":" + summerTour [option] + "
    " ) ; }

    var summerTour = (turkey: 2000, spain: 3000, egypt: 1000); var option; for (option in summerTour) (document.write (option + ":" + summerTour + "
    "); }

    Javascript prototypes (introduction)

    Consider an example of how javascript classes on prototypes

    Example: Create an object class Cаr (car) with three properties: name (name), model (model), color (color). Create an instance of the class with specific property values. Then through the created instance add to the class property owner (owner) with a specific default value ( Ivanov). Print all property values ​​of the created instance

    function Car (name, model, color) ( / * constructor of the car object * / this .name = name; this .model = model; this .color = color; ) var myCar = new Car; myCar.name = "Mers"; myCar.model = "600"; myCar.color = "green"; Car.prototype .owner = "Ivanov"; / * add a new property * / alert (myCar.name + "" + myCar.model + "" + myCar.color + "" + myCar.owner);

    function Car (name, model, color) (/ * constructor of the car object * / this.name = name; this.model = model; this.color = color;) var myCar = new Car; myCar.name = "Mers"; myCar.model = "600"; myCar.color = "green"; Car.prototype.owner = "Ivanov"; / * add a new property * / alert (myCar.name + "" + myCar.model + "" + myCar.color + "" + myCar.owner);

    Job js 6_2. To set js 6_1 through the created instance of the Employee object, add a new property address to the object class

    JavaScript object methods

    Object method creation

    Example: Add the aboutBrowser method to the Browser object constructor, which will display information about the properties of this object to the browser screen

      1 2 3 4 5 6 7 8 9 10 11 12 13 function showBrowser () (document.write ("Browser:" + this .name + "" + this .version);) function Browser (name, version) (this .name = name; this .version = version; this .aboutBrowser = showBrowser;) var myBrowser = new Browser ("Microsoft Internet Explorer", 8.0); myBrowser.aboutBrowser ();

      function showBrowser () (document.write ("Browser:" + this.name + "" + this.version);) function Browser (name, version) (this.name = name; this.version = version; this.aboutBrowser = showBrowser;) var myBrowser = new Browser ("Microsoft Internet Explorer", 8.0); myBrowser.aboutBrowser ();

    1. Object methods are created from the function and added to the class constructor

    function Browser (name, version) (this.name = name; this.version = version; this.aboutBrowser = function () (document.write ("Browser:" + name + "" + version);)) var myBrowser = new Browser ("Microsoft Internet Explorer", 8.0); myBrowser.aboutBrowser ();

    Job js 6_3. Create a class of objects (Tour) for the operation of a travel company with a method for calculating the cost of a trip from the calculation: number of people * number of days * country tariff... Instantiate the turkeyTour object with property values. Display all properties of the object on the screen. Create a calculation object method based on a function.

    Javascript prototypes of built-in objects

    Adding Properties and Methods to Built-in Objects (Prototype)

    JavaScript- OOP (object-oriented programming) language based on prototypes.
    Prototype- the object defining the structure

    Let's consider working with prototypes using an example:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 / * Change prototype * / // Add a default property to the embedded object String .prototype .color = "black"; // Add (change) a method to the built-in object String .prototype .write = stringWrite; function stringWrite () (document.write (" "); document.write (this .toString ()); document.write (" ") ; } // use the modified class var s = new String ("This is a string"); s.color = "red"; s.write ();

    / * Change prototype * / // Add a default property to the built-in String.prototype.color = "black"; // Add (change) a method to the built-in object String.prototype.write = stringWrite; function stringWrite () (document.write (" "); document.write (this.toString ()); document.write ("");) // use the modified class var s = new String (" This is a string "); s.color =" red "; s.write ();

    Important: Properties and methods cannot be added to the Math object


    Job js 6_4. Complete the program code to complete the task: Add the printMe () method to the built-in String class, which displays the word "Hooray!" as a heading (h ... tag) of a user-specified level ().
    The heading level (1, 2… 6) can be added as a property of the String class.
    Let's recap what heading tags should look like in HTML:

    Heading

    Complete the code:

    1 2 3 4 5 6 7 8 String .prototype .uroven = "1"; ... function printZagolovok () (... ...) var s = new ...; ...

    String.prototype.uroven = "1"; ... function printZagolovok () (... ...) var s = new ...; ...

    Bottom line: Let's compare again two use cases for custom objects in JavaScript:

    1. Creating collection objects
    2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 var myBook = new Object (); myBook.title = "(! LANG: book" ; myBook.price = "200" ; alert(myBook[ "title" ] ) ; !} // 1st option for accessing properties alert (meBook.price); // 2nd option for accessing properties function myBookShow () (for (var i in myBook) (document.write (i + ":" + myBook [i] + "
      " ) ; // iterate over properties)) myBook.show = myBookShow; myBook.show ();

      var myBook = new Object (); myBook.title = "(! LANG: book"; myBook.price="200"; alert(myBook["title"]); // 1-й вариант обращения к свойствам alert(meBook.price); // 2-й вариант обращения к свойствам function myBookShow() { for (var i in myBook) { document.write(i+": "+myBook[i]+"!}
      "); // iterate over properties)) myBook.show = myBookShow; myBook.show ();

    3. Creating Constructor Classes
    4. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 function myBook (title, price) ( // define properties this .title = title; this .price = price; // method definition this .show = show; function show () (document.write ("Title:" + this .title); document.write ("Price:" + this .price);)) var book = new myBook ("Book", 200); book.show ();

      function myBook (title, price) (// property definition this.title = title; this.price = price; // method definition this.show = show; function show () (document.write ("Title:" + this. title); document.write ("Price:" + this.price);)) var book = new myBook ("Book", 200); book.show ();> Go to home page</ a> <li> ... </ li> <li> ... </ li>

    5. Go to home page
    6. ...
    7. ...
    8. * Difficult: the number of menu items, their names and url need to ask the user

      Advice: to display a string on the screen in the show () method, use the document.write () method

      JavaScript Location, Navigator, Screen objects

      JavaScript Navigator

      Let's consider the use of the Navigator object in javaScript using an example:

      Example: Write a function that prints to the screen:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var option; // display all properties of the navigator object for (option in navigator) (document.write (option + ":" + navigator [option] + "
    " ) ; } // function for displaying specific properties of the navigator object function userDetails () (document.write ( "

    Browser name: "
    + navigator.userAgent + "
    "); document.write (" Browser language: "+ navigator.language +"
    "); document.write (" OS name: "+ navigator.oscpu +"
    "); document.write ( "Are cookies enabled:"+ navigator.cookieEnabled + "
    "); document.write ( "Is the Internet connected:"+ navigator.nLine + "
    ");) userDetails ();

    var option; // display all properties of the navigator object for (option in navigator) (document.write (option + ":" + navigator + "
    ");) // function for displaying specific properties of the navigator object function userDetails () (document.write ("

    Browser name: "+ navigator.userAgent +"
    "); document.write (" Browser language: "+ navigator.language +"
    "); document.write (" OS name: "+ navigator.oscpu +"
    "); document.write (" Are cookies enabled: "+ navigator.cookieEnabled +"
    "); document.write (" Is the Internet connected: "+ navigator.nLine +"
    ");) userDetails ();

    JavaScript Screen Object

    Let's consider the use of the Screen object in javaScript using an example:

    function userDetails () (document.write ("Resolution:" + screen.width + "x" + screen.height + "
    "); document.write (" Color depth: "+ screen.colorDepth +" x "+ screen.height +"
    ");) userDetails ();

    JavaScript Location object

    Let's consider using the Location object in javaScript with an example:

    1 2 3 4 function userDetails () (document.write ( "Address of the loaded page:"+ location.href + "
    ");) userDetails ();

    function userDetails () (document.write ("URL of the loaded page:" + location.href + "
    ");) userDetails ();

    Conclusions:

    • Using expressions with the new keyword, you can create instances of objects, that is, their concrete incarnations.
    • Moreover, thanks to the javascript prototype property, it is possible to add new properties and methods to objects that were invented by the user and were not present in the original built-in objects.
    • Object creation can be used to create databases.

    In this chapter:

    JavaScript has a number of predefined objects that you can use when writing scripts. These include objects such as Array, Boolean, Date, Function, Math, Number, RegExp, and String, as well as the primitive Object. V earlier versions language, it also included document objects (window, document), but now they are excluded from the core JavaScript language, and refer to the definition of the Document Object Model (DOM), which will be discussed later. However, some of the properties of these objects (document and window) are already familiar to us.

    However, let's get back to built-in JavaScript objects in the modern sense. All built-in objects except Math and Date have properties such as constructor and prototype. They are used to add new properties to existing objects, and are described in the context of a Function object.

    Object Object

    All JavaScript objects inherit from Object. Therefore, any other JavaScript object has all the properties and methods of this object.

    Only 2 properties are defined for the Object object - constructor and prototype. The constructor property defines a function that creates a prototype of an object - specifically the entire function, not just its name. In other words, consider the option when some test object is defined and an instance of this tmp object is created:

    Function test (version) (this.version = version;) tmp = new test (1);

    In this case, using the constructor property, you can see the source code of the test object (Figure 4.6):

    Alert (tmp.constructor);

    Rice. 4.6.

    However, this property has one limitation: it cannot display the code of built-in objects of the JavaScript language: in such cases, the output information is limited to the name of the prototype function and the string "".

    The prototype property allows access to the prototype function of the current object. Using this property makes it possible to change the characteristics of an object's prototype. For example, you can add a new property to an object of type test using the prototype property:

    Test.prototype.comment = "New property comment";

    Now all objects of type test, including the already created tmp instance, will have a comment property, which is easy to verify by applying the following check:

    Alert (tmp.comment);

    Moreover, it is possible to modify built-in JavaScript objects in this way. For example, if we need to add a property such as a description to the arrays, then we can do this (of course, only within the framework of the current scenario!) By referring to the prototype of the Array object and adding the corresponding property to it:

    Array.prototype.description = "";

    As for the methods, there are slightly more of them defined for the Object object - as many as 5 pieces. These are toSource, toString, watch, unwatch and valueOf, their short description are given in table 4.10.

    The toString and valueOf methods apply to almost all built-in JavaScript objects, and are usually called automatically by the interpreter when a conversion becomes necessary. The toSource method is actually just doing the work for the constructor property.

    The remaining watch and unwatch methods, proprietary extensions introduced in the Netscape 4 browser (now also supported by Mozilla), are intended for script debugging. Since the issue of debugging programs will not be considered within the framework of this publication, it makes no sense to describe these methods. But just in case, you can take note that in Sea Monkey (but not in Firefox browser) there is a script debugger - JavaScript Debugger.

    Array object

    Array variables contain ordered sets of values, represented as a single variable for convenience. We have already encountered arrays more than once (remember at least arrays of arguments), now it's time to deal with all their properties and subtleties of application.

    Unlike other programming languages, JavaScript does not have the same data type as an array. But this limitation is bypassed by the fact that you can use a predefined array object - Array. You can use one of the following syntaxes to create an array object:

    ArrayName = new Array (item1, item2, ... itemN) ArrayName = new Array (ArrayLength)

    In the first case, all the components of the array are listed, in the second, the number of elements is simply indicated. It is also allowed to use literals when declaring an array:

    Computers = ["PC", "Mac", "Sun"];

    To fill array elements with values, as well as to refer to array elements in general, you can use the element's index. It should be borne in mind that the index of the array elements starts from zero:

    Var colors = new Array (3); colors = "Red"; colors = "Blue"; colors = "Green";

    Quite often, it is convenient to use the ability provided by JavaScript to fill an array directly when it is declared:

    Var colors = new Array ("Red", "Blue", "Green");

    To find out the length of an array (the number of elements that make up an array), use the length property:

    Var NumColors = colors.length;

    In addition to the length property, JavaScript also provides a number of other properties and methods for working with arrays. In particular, the number of properties of the Array object, in addition to length, includes the constructor and prototype universal for all objects, as well as the index and input properties intended for using arrays in conjunction with regular expressions.

    As for the methods, in addition to the standard toSource, toString and valueOf, the arrays are endowed with a dozen of their own, listed in Table 4.11.

    Table 4.11. Array Object Methods
    MethodDescription
    concatConcatenates two arrays, and returns a new one
    joinConcatenates all elements of an array into one string
    popRemoves last element from an array, and returns it
    pushAdds one or more elements to the end of an array and returns its new length
    reverseMoves the elements of the array so that the first becomes the last, and vice versa
    shiftRemoves the first element of an array and returns it
    sliceRemoves some of the elements from an array, and returns a new array
    spliceAdds and / or removes an element from an array
    sortSorts the elements of an array alphabetically
    unshiftAdds one or more elements to the beginning of an array, and returns the new length of the array (in MSIE 5.5 and 6, this method does not return anything)

    Let's consider some of the methods in more detail. So, using the concat method, you can combine 2 arrays in one:

    Var a = new Array ("A1", "A2"); var b = new Array ("B1", "B2"); var ab = a.concat (b);

    Here the variable ab will become an array containing all 4 elements of the two arrays to be glued. If we now apply the join method to such an array, then the result will be a string containing all the elements of this array, separated by commas:

    Str = ab.join (); // get str = "A1, A2, B1, B2"

    As for the pop method, applying it to the same array, we will receive the response in "B2", and the array will be truncated to the first three values. And the shift method, on the contrary, returns the first element (in our case - "A1") and does the same with the array, with the only difference that the remaining elements are shifted forward.

    To better understand how these and other array methods work, turn to the next example in Listing 4.3.

    Listing 4.3. Working with arrays

    The same example can be viewed in the file array.html, at the same time it will be possible to view all the results of its work in the browser (see Fig. 4.7).

    Rice. 4.7. Result of splice method: returned array and changes

    Arrays can also be multidimensional, i.e. an array element can be another array. In this case, the following syntax is used to refer to an array element:

    Array2D = "Item 0,0" Array2D = "Item 0,1" ... Array2D [N] [N] = "Item N, N"

    Example of filling and output two-dimensional array can be found in the arrays.html file, there is also interactive example for almost all array methods.

    Boolean object

    Boolean object is a wrapper for the data type of the same name. The following syntax is used to define an object of type Boolean:

    BooleanObj = new Boolean (value)

    Here value is an initializing expression, which, if necessary, will be cast to true or false. If you specify a value such as 0, null, false, NaN, undefined, or an empty string, then the initialization of the Boolean object will be false, and for any other value, true.

    The primitive Boolean values ​​true and false should not be confused with the true and false data types of the Boolean object. For example, if you declare a variable x and assign it the value of a Boolean object initialized to false, it will still be true when compared:

    X = new Boolean (false); // when comparing if (x) we get true

    At the same time, if you simply assign a primitive data type to a variable, then it will receive it:

    X = false; // when comparing if (x) we get false

    As for the application of this object, in practice, it can be used as a function in order to convert values ​​of any other types to booleans:

    A = 100; x = Boolean (a); // x will get true if (x) (...)

    But, in fact, you are unlikely to do this, since, if necessary, such transformations are performed by the JavaScript interpreter automatically - in the example above, you could immediately write "if (a) ...", and the transformation necessary in this case will be done in any case ...

    Date object

    There is no special data type for working with dates in JavaScript, however, as with arrays, there is a special Data object. You can use any of the following methods to create a date object:

    New Date () new Date (Milliseconds) new Date ("Date_in_string_view")

    In the first case, a Date object is created with the current time, in the second, you must specify the number of milliseconds that have passed since January 1, 1970. If the date is specified as a string, then it should be of the form "Feb 28, 2005". It is also possible to specify a date using integer values ​​for year, month, day, etc .:

    New Date (Year, Month, Day [, Hour, Minute, Second, Millisecond])

    Of course, in this case, you can avoid specifying seconds and milliseconds, especially since milliseconds were not even supported in older versions of browsers. In addition, JavaScript prior to 1.3 does not support dates earlier than January 1, 1970. As for the format of the values ​​that are indicated in the string, the year is any 4-digit number (if you specify a 2-digit number, 1900 will be added to it), the month number is from 0 (January) to 11 (December), and the day is from 0 to 31. Accordingly, the time values ​​are also limited: for hours it will be an integer from 0 to 23, for seconds and minutes - from 0 to 59, and for milliseconds - from 0 to 999. Thus, as an object value of type Date to indicate May 9, 2005, you should write:

    Var anyday = new Date (2005, 5, 9);

    And if you need to get the current value of the date and time, then no parameters are required at all:

    Var now = new Date ();

    Starting with JavaScript 1.3, the date range can be within 100 million days before and after 01/01/1970 (almost 550 thousand years in total!). In the same version, there was a requirement to always indicate the year in four-digit format, in order to avoid errors associated with the change of centuries.

    To work with the Date object, 2 properties are provided - constructor and prototype, as well as many methods that allow you to select the desired part of the date (year, month, day, time), display it in one format or another, etc. They are all listed in Table 4.12.

    Table 4.12. Date Object Methods
    Method and its syntaxDescription
    getDate ()Returns the day of the month in local time
    getDay ()Returns the day of the week in local time
    getFullYear ()Returns the year in local time
    getHours ()Returns the current time (clock) in local time
    getMilliseconds ()Returns the current time (milliseconds) in local time
    getMinutes ()Returns the current time (minutes) in local time
    getMonth ()Returns the current time (month) in local time
    getSeconds ()Returns the current time (seconds) in local time
    getTime ()Returns the current time as an amount in local time
    getTimezoneOffset ()Returns the offset of the time in minutes from Greenwich Mean Time in local time
    getUTCDate ()Returns the day of the month in UTC
    getUTCDay ()Returns the day of the week in UTC
    getUTCFullYear ()Returns the year in UTC
    getUTCHours ()Returns the current time (hours) in UTC
    getUTCMilliseconds ()Returns the current time (milliseconds) in UTC
    getUTCMinutes ()Returns the current time (minutes) in UTC
    getUTCMonth ()Returns the current time (month) in UTC
    getUTCSeconds ()Returns the current time (seconds) in UTC
    getYear ()Outdated. Returns the year in short (two-digit) UTC format
    parse (date_string)Returns the number of milliseconds that elapsed from January 1, 1970 to the value specified in the parameter, in local time
    setDate (day)Sets the day of the month in local time
    setFullYear (year)Sets the year in local time
    setHours (hours)Sets the time (clock) in local time
    setMilliseconds (milliseconds)Sets the time (milliseconds) in local time
    setMinutes (minutes)Sets the time (minutes) in local time
    setMonth (month)Sets the time (month) in local time
    setSeconds (seconds)Sets the time (seconds) in local time
    setTime (milliseconds)Sets the time in milliseconds for a specific date in local time
    setUTCDate (day)Sets the day of the month to UTC
    setUTCFullYear (year)Sets the year in UTC
    setUTCHours (hours)Sets the time (hours) in UTC
    SetUTCMilliseconds (milliseconds)Sets the time (milliseconds) in UTC
    setUTCMinutes (minutes)Sets the time (minutes) in UTC
    setUTCMonth (month)Sets the time (month) in UTC
    setUTCSeconds (seconds)Sets the time (seconds) in UTC
    setYear (year)Outdated. Sets the year in local time, a two-digit format is allowed as the year value
    toGMTString ()Outdated. Converts a date to a Greenwich Mean Time string
    toLocaleString ()Returns the date and time as a string that matches the format of the settings on the local system
    toLocaleDateString ()Returns the date as a string that matches the format of the settings on the local system
    toLocaleTimeString ()Returns the time as a string that matches the format of the settings on the local system
    toSource ()Returns a date object in literal representation
    toString ()Returns a date object in string representation
    toUTCString ()Converts a date to a string in UTC format
    UTC (parameters)Returns the number of milliseconds since January 1, 1970 UTC. The parameters are the year, month and day, and (optionally) - hours, minutes, seconds and milliseconds.
    valueOf ()Returns the date as a primitive value

    Despite such an abundance of methods, working with the Date object is quite simple: you just need to understand the principle of naming the methods:

    • methods starting with "set" are for setting the date and time in Date objects;
    • methods starting with "get" are for retrieving dates, times, or parts of them from Date objects;
    • methods starting with "to" return date and time (or parts of them) as string values;
    • methods containing "UTC" differ from similar ones only in that they work with the universal time format (that is, displays the time in Greenwich Mean Time, taking into account the offset relative to the current time zone).

    Thus, it remains only to add to get or set the name of the necessary part of the date or time in order to get or set desired parameter using UTC as well if necessary. Well, when you need to get the result in a "human" form, use the to methods. You should also remember that to work with the year you should always use only full-format functions (i.e. getFullYear or getUTCFullYear, not getYear).

    The string representation of a date in JavaScript has the following format:

    Day Week Month Day Year Hours: Minutes: Seconds GMT ± Offset

    To see how dates are represented, and at the same time to see how functions like toString work, consider what they all return to the output. In this case, the first thing that can come to mind to view the operation of a particular function is to use the text output to the document:

    Document.writeln (DateObject.toString ()); document.writeln (DateObject.toGMTString ()); // etc.

    But, in fact, since there are many functions, it would be good to write in advance what kind of action was performed:

    Document.writeln ("DateObject.toString ()" + DateObject.toString ());

    Now let's think again about how many lines we really want to display in this way. Even taking into account the possibilities of the "copy and paste" method, which is supported by all text editors, it will not insure against errors like this:

    Document.writeln ("DateObject.toLocaleString ()" + DateObject.toString ());

    But, as the IBM motto says, people should think and machines should work. So let's think about how to make the computer work, while at the same time saving ourselves the need to enter extra code bytes, for which we turn to Listing 4.4.

    Listing 4.4. Displaying different types of dates and the eval function

    Date Object Methods

    First of all, it defines the printDate function, which actually displays the date in the document in one form or another. Rather, it displays the date in our case, but in principle it can display anything you want - the main thing is that the argument it accepts is a complete piece of JavaScript code. At the same time, first the code is output as it is (i.e., the string variable is printed in its original form), and then the result of execution is output, for which the eval function is used. As a result, having written such a function once, you can refer to it in the future throughout the entire document, saving yourself from having to enter practically the same text twice.

    Following the output function is the creation of an object of the Date type, which is assigned the value 2005, 3 months (April, since January is zero), 1 day, 14 hours, 30 minutes, 45 seconds. Next, a document is opened for writing and the printDate function is sequentially called for 6 different methods Date object. The result of this script will be 6 lines containing pairs of values ​​from the method and the result of its operation, separated by a colon (Fig. 4.8).

    Rice. 4.8. Displaying the same date using different methods

    It should be noted that the toSource method, which displays the date in the internal representation of the program, is only supported by Mozilla browsers. In addition, the format for displaying dates by all other methods may also differ slightly in different browsers. You can load such an example into various viewers and see for yourself what they produce (date.html file).

    Function object

    The predefined Function object defines a line of JavaScript code that must be executed as a function. The following syntax is used to declare a Function object:

    FunctionName = new Function ([arg1, arg2, ... argN], FunctionBody)

    In this case, the name of any variable or a property of an existing object can be used as the name of the function. It is also possible to specify an object of type Function as the value for the object's event handler. For example, if we want to make our own event handler for the document loading completion event (document.onload), we can write this:

    Document.onload = new Function ([Argument1, ... argN], FunctionBody);

    The arguments in this case are the parameters passed to the function, and the body of the function is the actual code that must be executed when accessing this function object. For example, you can write a variant of an object that will be used to square a number:

    Var SquareObj = new Function ("x", "return x * x");

    Here SquareObj is the name of the variable, x is the accepted argument, and "return x * x" is the body of the function. Pay attention to the fact that not only the body of the function, but also the arguments it takes are enclosed in quotation marks, and also that the name of the object type, as is customary in JavaScript, is capitalized (Function).

    Using variables created in this way is similar to using variables of any other types:

    Var a = 5 + SquareObj (2); // get 9

    In fact, an object of type Function can always be represented as a regular function, declared using keyword function. So, the same raising to the second power can be described as follows:

    Function SquareFunc (x) (return x * x;)

    Accordingly, it is possible to use a function declared by this method (in this case, it is a function in its "pure" form, and not a procedure), in a similar way:

    Var a = 5 + SquareFunc (2); // also get 9

    Thus, assigning a value to a variable as a function using a Function object is the same as declaring a function as such. But at the same time, these approaches have a difference: if SquareObj is a variable whose value is a reference to an object created using the Function object, then SquareFunc is the name of the function. Accordingly, during program execution, they also behave differently: for an object of the function type, the interpreter, whenever it encounters a variable (in our case, SquareObj), will fully evaluate the entire function code, and for functions declared in the usual way, the code is evaluated only at the first aisle. This difference may not be fundamental if the function performs one-time work, however, using variables created on the basis of the Function object significantly reduces the efficiency of the program in loops. Therefore, in practice, the use of function objects is very rare, but, nevertheless, sometimes they can be convenient, for example, for adding methods to other objects.

    The Function object has standard JavaScript constructor and prototype properties, as well as a number of its own:

    Arguments - an array corresponding to the parameters of the arguments.callee function - corresponds to the body of the function. arguments.caller (deprecated) - indicates the name of the function from which the object was called; arguments.length - indicates the number of parameters to the function. length - indicates the number of arguments expected by the function (and not the number received, as is the case with argument.length);

    ATTENTION
    All arguments properties can only be seen "from inside" a function, and since JavaScript 1.4, arguments are no longer a property of the Function object, but an independent local variable that is implicitly present in any function. In fact, there is only 1 property left for Function - length.

    In addition to properties, the Function object has several methods. So, the apply method allows you to apply the method of one object to another, and the call method allows you to call the method of another object in the context of the current one. Unfortunately, the implementation of these methods in practice clearly leaves much to be desired. So it only remains to mention the standard JavaScript methods toString, toSource and valueOf, which are also available in the Function object.

    Math object

    Math is a built-in JavaScript object that has basic mathematical constants and functions as methods and properties. For example, the PI property of the Math object contains the value of pi (π), which is approximately 3.1416, and the sin method returns the sine of the specified number.

    In addition to the number π, the Math object has the following properties:

    • E is the base of natural logarithms (approximately 2.718)
    • LN10 - natural logarithm of 10 (approximately 2.302)
    • LN2 - natural logarithm of 2 (approximately 0.693)
    • LOG10E - Decimal logarithm of E (approximately 0.434)
    • LOG2E - binary logarithm of E (approximately 1.442)
    • SQRT1_2 - Square root of 0.5 (approximately 0.707)
    • SQRT2 - Square Root of 2 (approximately 1.414)

    Since all the properties of the Math object are predefined constants, it is not only not required to create other objects of the Math type, but it is also unacceptable, and you must always refer to them in the same way, for example:

    Var CircleLength = diameter * Math.PI;

    In addition to properties, the Math object also defines methods that correspond to basic mathematical functions. All of them are listed in table 4.13.

    Table 4.13. JavaScript math methods
    Method and its syntaxDescription
    abs (number)Returns the absolute value of the argument
    atan2 (y, x)Returns a number in the range -? to?, representing the angle (in radians) between the x-axis and point (x, y). Note that the first argument is the Y-coordinate
    exp (number)Returns E to the specified power (exponential logarithm)
    ceil (number), floor (number)Returns a value that is the nearest greater (ceil) or lower (floor) integer
    min (number1, number2), max (number1, number2)Returns the lesser (min) or greater (max) number of two compared arguments
    sin (number), cos (number), tan (number), asin (number), acos (number), atan (number)Returns the result of executing standard trigonometric functions - sine, cosine, tangent, arcsine, arccosine, and arctangent
    pow (base, exponent)Returns the base exponential
    random ()Returns a pseudo-random number between 0 and 1
    round (number)Returns the value rounded to the nearest integer
    sqrt (number)Returns the square root of a number

    As with properties, to use the methods of the Math object, you must refer directly to the object itself, not a copy of it. For example, let's write a function that will return the diameter based on the area of ​​the circle:

    Function CircleDiam (Square) (Radius = Math.sqrt (Square / Math.PI);)

    To use it in practice, you can use the prompt and alert methods:

    Var sq = prompt ("Enter area", 1); var di = CircleDiam (sq); alert ("Circle diameter:" + di);

    The operation of these and other methods of the Math object can be viewed in the math.html file.

    Number object

    The Number object is an object representation of simple numeric types. It has special properties for numeric constants such as "maximum number", "not a number" and "infinity". To create a new object of type Number, use the following syntax:

    New Number

    In practice, using the Number object most often boils down to using its constants when validating arguments and tracking run-time errors. For example, to check if the value of a variable is a number or not, you can use this method:

    If (x! = Number.NaN);

    In this case, the condition will be true if the variable x contains a number, since it is compared with a special value - NaN, which means "not a number". Besides NaN, you can use other special values, all of which are properties of the Number object:

    • MAX_VALUE - the maximum possible number
    • MIN_VALUE - the minimum possible number
    • NaN is not a number
    • NEGATIVE_INFINITY - "negative infinity", a special value returned in case of overflow
    • POSITIVE_INFINITY - "positive infinity", special value returned in case of overflow

    All of these properties are constants, so you don't need to create a new Number object to use them. In addition to the above properties, the standard constructor and prototype properties are also defined for Number.

    In addition to properties, the Number object, of course, has methods. In addition to standard methods toSource, toString, and valueOf, JavaScript 1.5 introduces 3 new native methods of the Number object - toExponential, toFixed, and toPrecision. All of them are designed to convert numbers to strings based on one format or another. For example, the toExponential method converts a number to a string as a number with an exponent, the toFixed method converts to a string containing a number with a fixed number of decimal places, and the toPrecision method uses one of these methods, depending on the number and the number of digits allocated.

    Let's explore these methods in more detail, for which we will consider their syntax:

    Method ([Number of Characters])

    Obviously, for all methods, the number of characters denotes the number of decimal places, but if the default value for the toFixed method (that is, if nothing is specified) is 0, then for toExponential and toPrecision it is the number of characters required to display the entire number. To better understand how each of these methods work and how they differ, let's look at them in Listing 4.5:

    Listing 4.5. The toExponential, toFixed, and toPrecision methods

    Number Object Methods

    Here we again (as in Listing 4.4) used a function that prints first an expression and then the result of its interpretation, only in this case we called it printNumber. This is followed by the actual declaration of the variable over which the calculations will be performed. In this case, we declared it as an object of type Number, although, in fact, we could have limited ourselves to a simple variable declaration (x = 12.45678). Finally, the document is opened for writing and the value of the variable x is first displayed in it without any explicit conversions (but we already know that in fact the toString () method is automatically applied here), after which all three methods under investigation are called first without specifying a number characters, and then - with parameters 2 and 4. The result of this script will be 10 lines containing pairs "expression: processing result" (Fig. 4.9).

    Rice. 4.9.

    In conclusion, it remains to note once again that these methods appeared only in JavaScript 1.5 and, accordingly, do not work in the browsers Netscape 4, MSIE 4/5 and Opera before version 7.0. At the same time, they provide more flexible formatting options for numbers in output than, say, the round () method of the Math object.

    2011-08-01 // Any questions, suggestions, comments? You can

    Back in the days of XHTML / HTML4, there were only a few features that developers could use to store arbitrary DOM-related data. You could invent your own attributes, but that was risky - your code would not be valid, browsers could ignore your data, and this could cause problems if the name matched the standard HTML attributes.

    Therefore, most developers tied to the class or rel attributes as they were the only sane way to store additional lines... For example, suppose we are creating a widget to display posts such as the timeline of Twitter posts. Ideally, JavaScript should be configurable without having to rewrite the code, so we define the user ID in the class attribute, for example:

    Our JavaScript code will search for element with ID msglist... With the help of the script, we will search for classes starting with user_, and "bob" in our case will be the user ID, and we will display all the messages of this user.

    Let's say we would also like to set the maximum number of messages, and skip messages older than six months (180 days):

    Our attribute class gets cluttered very quickly - it's easier to make a mistake, and JavaScript string parsing becomes more and more difficult.

    HTML5 Data Attributes

    Fortunately, HTML5 introduced the ability to use custom attributes. You can use any lowercase name with the prefix data-, for example:

    Custom data attributes:

    • these are strings - in them you can store any information that can be represented or encoded as a string, for example JSON. Typecasting must be done using JavaScript
    • should be used in cases where no suitable HTML5 elements or attributes are available
    • refer only to the page. Unlike microformats, they should be ignored. external systems, like search engines and search robots

    JavaScript example # 1: getAttribute and setAttribute

    All browsers allow you to get and change data attributes using the getAttribute and setAttribute methods:

    Var msglist = document.getElementById ("msglist"); var show = msglist.getAttribute ("data-list-size"); msglist.setAttribute ("data-list-size", + show + 3);

    This works, but should only be used to maintain compatibility with older browsers.

    JavaScript example # 2: jQuery data () method

    Since jQuery 1.4.3, the data () method handles HTML5 data attributes. You don't need to explicitly specify the prefix data- so a code like this would work:

    Var msglist = $ ("# msglist"); var show = msglist.data ("list-size"); msglist.data ("list-size", show + 3);

    Be that as it may, keep in mind that jQuery tries to convert the values ​​of such attributes to suitable types (booleans, numbers, objects, arrays, or null) and will affect the DOM. Unlike setAttribute, method data () will not physically replace the attribute data-list-size- if you check its value outside of jQuery - it still stays at 5.

    JavaScript example # 3: API for working with datasets

    Finally, we have an API for working with HTML5 datasets that returns a DOMStringMap object. It must be remembered that data-attributes are mapped to an object without prefixes. data-, hyphens are removed from the names, and the names themselves are converted to camelCase, for example:

    Attribute name Dataset API name
    data-user user
    data-maxage maxage
    data-list-size listSize

    Our new code:

    Var msglist = document.getElementById ("msglist"); var show = msglist.dataset.listSize; msglist.dataset.listSize = + show + 3;

    This API is supported by all modern browsers but not IE10 and below. There is a workaround for these browsers, but it's probably more practical to use jQuery if you're writing for older browsers.

    When working with date and time in JavaScript used by Date object... I don't think I need to explain how often you have to work with date and time. And in this article you will learn how to do it in JavaScript.

    Let's start, by tradition, with the constructors Date object... There are four of them. The first constructor takes no parameters and it returns the current time and date:

    Var date = new Date ();
    document.write (date);

    As a result, you will see something like this: " Thu Oct 14 2010 11:42:06 GMT + 0400".

    Second constructor Date object is a constructor with one parameter. This parameter contains the number of milliseconds that have passed since 01.01.1970 (the beginning of the era Unix). For example, like this:

    Var date = new Date (135253235);
    document.write (date);

    As a result, you will see the following: " Fri Jan 02 1970 16:34:13 GMT + 0300".

    The following constructor allows you to create Date object with the setting of the following parameters: year, month and day:

    Var date = new Date (2010, 0, 12);
    document.write (date);

    Result: " Tue Jan 12 2010 00:00:00 GMT + 0300". Also note that 0th month is January, and 11th is December.

    And the last constructor Date class in JavaScript allows you to create Date object with all date and time parameters: year, month, day, hours, minutes and seconds.

    Var date = new Date (2010, 0, 12, 23, 45, 12);
    document.write (date);

    You get the following line: " Tue Jan 12 2010 23:45:11 GMT + 0300". That's all JavaScript Date object constructors provided by the developers.

    Special properties of Date class no, so let's go straight to the methods. Let's start right away with a group of methods that work exactly the same, but each of them returns its own date and time element:

    Var date = new Date ();
    document.write ("Year -" + date.getFullYear () + "
    ");
    document.write ("Month -" + date.getMonth () + "
    ");
    document.write ("Number -" + date.getDate () + "
    ");
    document.write ("Day of the week -" + date.getDay () + "
    ");
    document.write ("Hour -" + date.getHours () + "
    ");
    document.write ("Minute -" + date.getMinutes () + "
    ");
    document.write ("Second -" + date.getSeconds () + "
    ");
    document.write ("Millisecond -" + date.getMilliseconds () + "
    ");
    document.write ("Number of milliseconds passed since 01.01.1970 -" + date.getTime () + "
    ");

    By running this script, you will instantly understand what each of these methods does. The only thing I want to note is that the numbering of the days of the week also starts with scratch... Moreover, Sunday has an index 0 and Saturday - 6 .

    There are similar methods, but showing date and time by Greenwich Mean Time... Let's write code like this:

    Var date = new Date ();
    document.write ("Year -" + date.getUTCFullYear () + "
    ");
    document.write ("Month -" + date.getUTCMonth () + "
    ");
    document.write ("Number -" + date.getUTCDate () + "
    ");
    document.write ("Day of the week -" + date.getUTCDay () + "
    ");
    document.write ("Hour -" + date.getUTCHours () + "
    ");
    document.write ("Minute -" + date.getUTCMinutes () + "
    ");
    document.write ("Second -" + date.getUTCSeconds () + "
    ");
    document.write ("Millisecond -" + date.getUTCMilliseconds () + "
    ");

    By running this script, you will find out the current date and time in Greenwich.

    Opposite methods get () are the methods - set ()... If the former return certain values, the latter, on the contrary, change them. Actually, I could not bring this script, but so that there are no questions left, let's do it:

    Var date = new Date ();
    date.setFullYear (1990);
    date.setMonth (11);
    date.setDate (15);
    date.setHours (9);
    date.setMinutes (20);
    date.setSeconds (0);
    date.setMilliseconds (10);
    document.write (date);

    I hope you noticed that the method setDay () does not exist. This means that the day of the week is selected depending on the year, month and day.

    There are also similar methods for Greenwich. Only the prefix is ​​added UTC, for example, to change the month, use the method setUTCMonth ().

    And the last method is setTime ()... Takes as a parameter the number of milliseconds passed since 01.01.1970 :

    Date.setTime (39293012);
    document.write (date);

    As a result, you will see this: " Thu Jan 01 1970 13:54:53 GMT + 0300".

    That's all the constructors and methods Date object in JavaScript.