A brief introduction to JavaScript objects (i)

Source: Internet
Author: User
Tags local time

JavaScript objects
All things in JavaScript are objects: strings, numbers, arrays, functions ...
In addition, JavaScript allows custom objects to be customized.
All things are objects
JavaScript provides multiple built-in objects, such as String, Date, Array, and so on. Objects are just special data types with properties and methods.
The Boolean type can be an object.
A digital type can be an object.
A string can also be an object
Date is an object
Math and regular expressions are also objects
An array is an object
Even a function can be an object
JavaScript objects
object is just a special kind of data. Object has properties and methods.
Accessing the properties of an object
A property is a value associated with an object.
The syntax for accessing object properties is:
Objectname.propertyname
This example uses the Length property of the string object to get the lengths of the strings:
var message= "Hello world!";
var x=message.length;
After the above code is executed, the value of X will be:
12

Methods for accessing objects
Method is an action that can be performed on an object.
You can invoke a method by using the following syntax:
Objectname.methodname ()
This example uses the toUpperCase () method of the String object to convert the text to uppercase:
var message= "Hello world!";
var x=message.touppercase ();
After the above code is executed, the value of X will be:
HELLO world!

Creating JavaScript Objects
With JavaScript, you can define and create your own objects.
There are two different ways to create a new object:
Defining and creating an instance of an object
Use a function to define an object, and then create a new object instance
Create a direct instance
This example creates a new instance of the object and adds four properties to it:
Instance
Person=new Object ();
Person.firstname= "John";
Person.lastname= "Doe";
person.age=50;
Person.eyecolor= "Blue";

Using the Object Builder
This example uses a function to construct an object:
Instance
function person (firstname,lastname,age,eyecolor)
{
This.firstname=firstname;
This.lastname=lastname;
This.age=age;
This.eyecolor=eyecolor;
}
In JavaScript, this usually points to the function we are executing, or to the object that the function belongs to (runtime)
Creating an instance of a JavaScript object
Once you have the object constructor, you can create a new object instance, just like this:
var myfather=new person ("John", "Doe", "Blue");
var mymother=new person ("Sally", "Rally", and "green");

Add attributes to JavaScript objects
You can add a new property to an existing object by assigning a value to the object:
Suppose Personobj already exists-you can add these new properties to it: FirstName, LastName, Age, and Eyecolor:
Person.firstname= "John";
Person.lastname= "Doe";
person.age=30;
Person.eyecolor= "Blue";

X=person.firstname;
After the above code is executed, the value of X will be:
John

Add a method to a JavaScript object
method is simply a function attached to an object.
Methods for defining objects inside the constructor function:
function person (firstname,lastname,age,eyecolor)
{
This.firstname=firstname;
This.lastname=lastname;
This.age=age;
This.eyecolor=eyecolor;

This.changename=changename;
function ChangeName (name)
{
This.lastname=name;
}
}
The value of the ChangeName () function name is assigned to the LastName property of the person.
Now you can try it:
Mymother.changename ("Doe");
JavaScript class
JavaScript is an object-oriented language, but JavaScript does not use classes.
In JavaScript, classes are not created and objects are not created through classes (as in other object-oriented languages).
JavaScript is based on prototype, not class-based.
JavaScript for...in Loops
The JavaScript for...in statement loops through the properties of the object.
Grammar
For (variable in object)
{
Execute the code ...
}
Note: The code blocks in the for...in loop are executed once for each property.
Instance
Iterate through the properties of an object:
Instance
var person={fname: "John", lname: "Doe", age:25};

for (x in person)
{
Txt=txt + person[x];
}

The

JavaScript Number Object
JavaScript has only one numeric type. The
can be used or you can write a number without using a decimal point. The
JavaScript number
JavaScript numbers can be used or can be written without using a decimal point:
instance
var pi=3.14;//using the decimal point
Var x=34;//Do not use the decimal point
The maximum or minimum number can be written by the scientific (exponential) notation:
Instance
var y=123e5;//12300000
var z=123e-5;//0.00123
All JavaScript numbers are 64-bit
JavaScript is not a type language. Unlike many other programming languages, JavaScript does not define different types of numbers, such as integers, short, long, floating point, and so on.
in JavaScript, numbers are not classified as integer types and floating-point types, and all numbers are floating-point types. JavaScript uses the 64-bit floating-point format defined by the IEEE754 standard to represent numbers, which can represent a maximum value of ±1.7976931348623157 x 10308 and a minimum of ±5 x 10-324

Precision
Integers (not using decimal or exponential notation) are up to 15 bits.
Instance
var x = 999999999999999; X is 999999999999999
var y = 9999999999999999; Y is 10000000000000000
The maximum number of decimal digits is 17, but the floating-point operation is not always 100% accurate:
Instance
var x = 0.2+0.1; Output is 0.30000000000000004
Octal and hexadecimal
If the prefix is 0, JavaScript interprets numeric constants as octal numbers, and if the prefixes are 0 and "X", they are interpreted as hexadecimal numbers.
Instance
var y = 0377;
var z = 0xFF;
Never write 0 in front of the number unless you need to make an octal conversion.
By default, JavaScript numbers are displayed in decimal.
But you can use the ToString () method to output 16 binary, 8 binary, and 2 binary.
Instance
var mynumber=128;
Mynumber.tostring (16); Returns 80
Mynumber.tostring (8); Returns 200
Mynumber.tostring (2); Returns 10000000

Infinity (Infinity)
When the result of a numeric operation exceeds the upper limit (overflow) of the number that JavaScript can represent, the result is a special infinity (infinity) value, expressed as infinity in JavaScript. Similarly, when the value of a negative number exceeds the range of negative numbers that JavaScript can represent, the result is negative infinity, represented by-infinity in JavaScript. The behavior characteristics of infinite values are consistent with what we expect: based on their addition, subtraction, multiplication, and divide operations, or infinity (and, of course, their positive and negative numbers).
Instance
mynumber=2;
while (mynumber!=infinity)
{
Mynumber=mynumber*mynumber; Repeat calculation until MyNumber equals Infinity
}

Dividing by 0 also produces infinity:
Instance
var x = 2/0;
var y =-2/0;

NaN-Non-numeric value
The NaN property is a special value that represents a non-numeric value. This property is used to indicate that a value is not a number. You can set the number object to this value to indicate that it is not a numeric value.
You can use the IsNaN () global function to determine whether a value is a NaN value.
Instance
var x = +/"Apple";
IsNaN (x); Returns True
var y = 100/"1000";
IsNaN (y); Returns false

Divide by 0 is infinity, Infinity is a number:
Instance
var x = 1000/0;
IsNaN (x); Returns false

Numbers can be numbers or objects
Numbers can be initialized with private data, just like x = 123;
JavaScript numeric object initialization data, var y = new number (123);
Instance
var x = 123;
var y = new number (123);
typeof (X)//return number
typeof (Y)//return Object

Instance
var x = 123;
var y = new number (123);
(x = = y)//is False, because X is a number and Y is an object

Numeric properties
Max_value
Min_value
Negative_infinity
Positive_infinity
NaN
Prototype
Constructor
Digital method
Toexponential ()
ToFixed ()
Toprecision ()
ToString ()
ValueOf ()

JavaScript strings (String) object
A String object is used to handle an existing block of characters.
JavaScript string
A string is used to store a series of characters like "John Doe".
A string can use either single or double quotation marks:
Instance
var carname= "Volvo XC60";
var carname= ' Volvo XC60 ';
You use the location (index) to access any character in the string:
Instance
var character=carname[7];
The index of the string starts at zero, so the first character of the string is [0], the second character is [1], and so on.
You can use quotation marks in a string, as in the following example:
Instance
var answer= "It ' s Alright";
var answer= "He is called ' Johnny '";
var answer= ' He is called ' Johnny ';
Or you can use the escape character (\) in the string to quote:
Instance
var answer= ' it\ ' s alright ';
var answer= "He is called \" johnny\ "";

Strings (String)
String (string) to calculate the length of the string using length property:
Instance
var txt= "Hello world!";
document.write (txt.length);

var txt= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write (txt.length);

Find a string in a string
The string uses indexOf () to position the first occurrence of a specified character in a string:
Instance
var str= "Hello World, Welcome to the universe";
var n=str.indexof ("Welcome");

If the corresponding character function is not found, return-1
The LastIndexOf () method starts at the end of the string to find where the string appears.
Content Matching
The match () function is used to find a specific character in a string and, if found, returns the character.
Instance
var str= "Hello world!";
document.write (Str.match ("World") + "<br>");
document.write (Str.match ("World") + "<br>");
document.write (Str.match ("world!"));

Replace content
The replace () method replaces some character with some characters in a string.
Instance
Str= "Please visit microsoft!"
var n=str.replace ("Microsoft", "W3cschool");

String Case Conversion
The string case conversion uses the function touppercase ()/toLowerCase ():
Instance
var txt= "Hello world!"; String
var txt1=txt.touppercase (); Txt1 text is converted to uppercase
var txt2=txt.tolowercase (); Txt2 text is converted to lowercase

String to Array
The string is converted to an array using the split () function:
Instance
txt= "A,b,c,d,e"//String
Txt.split (","); Use commas to separate
Txt.split (""); Use spaces to separate
Txt.split ("|"); Use vertical bars to separate

Special characters
In Javascript, you can use backslashes (\) to insert special symbols, such as apostrophes, quotation marks, and other special symbols.
Look at the following JavaScript code:
var txt= "We is the so-called" Vikings "from the north.";
document.write (TXT);
In JavaScript, the start and stop of a string use single or double quotation marks. This means that the above string will be cut into: We are the so-called
To resolve the above problems, you can use backslashes to escape quotation marks:
var txt= "We is the so-called \" Vikings\ "from the north.";
document.write (TXT);
JavaScript will output the correct text string: We are the "Vikings" from the so-called.
The following table lists other special characters that you can use to escape special characters by using backslashes:
Code output
\ ' Single quotation mark
\ "Double quotation marks
\ \ Diagonal Bar
\ nthe line break
\ r Enter
\ttab
\b Spaces
\f Page Change

String properties and Methods
Property:
Length
Prototype
Constructor
Method:
CharAt ()
charCodeAt ()
Concat ()
fromCharCode ()
IndexOf ()
LastIndexOf ()
Match ()
Replace ()
Search ()
Slice ()
Split ()
SUBSTR ()
SUBSTRING ()
toLowerCase ()
toUpperCase ()
ValueOf ()

JavaScript Date (date) object
Date Object Properties
Property Description
Constructor returns a reference to the Date function that created this object.
Prototype gives you the ability to add properties and methods to objects.
Date Object method
Method description
GetDate () Returns the day of the one month (1 ~ 31) from the Date object.
GetDay () Returns the day of the week (0 ~ 6) from the Date object.
getFullYear () returns the year as a four-digit number from a Date object.
GetHours () returns the hour (0 ~ 23) of the Date object.
Getmilliseconds () returns the milliseconds (0 ~ 999) of the Date object.
Getminutes () returns the minute (0 ~ 59) of the Date object.
GetMonth () returns the month (0 ~ 11) from the Date object.
Getseconds () returns the number of seconds (0 ~ 59) of the Date object.
GetTime () returns the number of milliseconds since January 1, 1970.
getTimezoneOffset () returns the minute difference between local time and Greenwich Mean Time (GMT).
getUTCDate () Returns the day of the month (1 ~ 31) from the Date object according to the world.
GetUTCDay () Returns the day of the week (0 ~ 6) from the Date object according to the world.
getUTCFullYear () returns a four-digit year from a Date object according to the world.
getUTCHours () returns the hour (0 ~ 23) of the Date object according to the universal.
getUTCMilliseconds () returns the milliseconds (0 ~ 999) of a Date object based on the universal.
getUTCMinutes () returns the minute (0 ~ 59) of the date object according to the universal.
getUTCMonth () returns the month (0 ~ 11) from the Date object, depending on the world.
getUTCSeconds () returns the second (0 ~ 59) of the Date object according to the universal.
GetYear () is obsolete. Please use the getFullYear () method instead.
Parse () returns the number of milliseconds from midnight January 1, 1970 to the specified date (string).
SetDate () Sets the day of the month in the Date object (1 ~ 31).
setFullYear () sets the year (four digits) in the Date object.
Sethours () sets the hour (0 ~ 23) in the Date object.
Setmilliseconds () sets the milliseconds (0 ~ 999) in the Date object.
Setminutes () sets the minute (0 ~ 59) in the Date object.
Setmonth () sets the month (0 ~ 11) in the Date object.
Setseconds () sets the second (0 ~ 59) in the Date object.
The SetTime () settime () method sets the Date object in milliseconds.
SetUTCDate () Sets the day of the month in the Date object according to the world time (1 ~ 31).
setUTCFullYear () sets the year (four digits) in the Date object according to the world time.
setUTCHours () sets the hour (0 ~ 23) in the Date object according to the world time.
setUTCMilliseconds () sets the milliseconds (0 ~ 999) in the Date object according to the world time.
setUTCMinutes () sets the minute (0 ~ 59) in the Date object according to the world time.
setUTCMonth () sets the month (0 ~ 11) in the Date object according to the world time.
The setUTCSeconds () setUTCSeconds () method is used to set the seconds field for a specified time based on Universal Time (UTC).
Setyear () is obsolete. Please use the setFullYear () method instead.
toDateString () Converts the date part of a Date object to a string.
toGMTString () is obsolete. Please use the toutcstring () method instead.
Toisostring () returns the date format of a string using the ISO standard.
ToJSON () returns a date string in JSON data format.
toLocaleDateString () Converts the date part of a Date object to a string, based on the local time format.
toLocaleTimeString () Converts the time portion of a Date object to a string, based on the local time format.
toLocaleString () Converts a Date object to a string, according to the local time format.
ToString () Converts the Date object to a string.
toTimeString () Converts the time portion of a Date object to a string.
toUTCString () Converts the Date object to a string based on the universal.
UTC () returns the number of milliseconds from January 1, 1970 to the specified date, depending on the time.
ValueOf () returns the original value of the Date object.

Date Created
The Date object is used to process dates and times.
You can define a Date object by using the New keyword. The following code defines a Date object named MyDate:
There are four ways to initialize a date:
New Date ()//current date and time
New Date (milliseconds)//returns the number of milliseconds since January 1, 1970
New Date (datestring)
New Date (year, month, day, hours, minutes, seconds, milliseconds)
Most of the above parameters are optional, and in the case of unspecified, the default parameter is 0.
Instantiate some examples of a date:
var today = new Date ()
var D1 = new Date ("October 13, 1975 11:13:00")
var d2 = new Date (79,5,24)
var d3 = new Date (79,5,24,11,33,0)

Set Date
By using a method for a Date object, we can easily manipulate the date.
In the following example, we set a specific date for the Date object (January 14, 2010):
var mydate=new Date ();
Mydate.setfullyear (2010,0,14);
In the following example, we set the Date object to a date after 5 days:
var mydate=new Date ();
Mydate.setdate (Mydate.getdate () +5);
Note: If you increase the number of days to change the month or year, the Date object will automatically complete the conversion.
Two comparison of dates
A Date object can also be used to compare two dates.
The following code compares the current date with January 14, 2100:
var x=new Date ();
X.setfullyear (2100,0,14);
var today = new Date ();

if (x>today)
{
Alert ("Today is before January 14, 2100");
}
Else
{
Alert ("Today is after January 14, 2100");
}

A brief introduction to JavaScript objects (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.