Foreground interface (5) --- object and random number, foreground Random Number

Source: Internet
Author: User
Tags hasownproperty

Foreground interface (5) --- object and random number, foreground Random Number


1. object

1.1. Object Attributes

1.1.1. vertex operator (.)

1.1.2. Brackets operator ([])

1.1.3. Update Object Attributes

1.1.4. Add Object Attributes

1.1.5. Delete Object Attributes

1.1.6. Key-Value Pair object

1.1.7. Determine whether the attributes have hasOwnProperty

1.2. Object formatting: JSON

1.2.1. Access the nested attributes of JSON objects

1.3. Create an object for the constructor

1.3.1. Call object constructor

1.3.2. constructor with Parameters

2. Random Number

2.1. Random decimal places

2.2. Random integer

2.3. Random Number in the specified range

----------------------- Golden line ----------------------


1. Object Object  

Objects are similar to arrays. arrays access and modify data through indexes, and objects access and modify data through attributes.

This is an example object:

Var cat = {
"Name": "Whiskers ",
"Legs": 4,
"Tails": 1,
"Enemies": ["Water", "Dogs"]

Objects are suitable for storing structured data. They are exactly the same as objects in the real world, such as a cat.

1.1. Object Attributes

There are two ways to access object attributes: vertex operator (.) and brackets operator ([]).

1.1.1. Point operator ( . )

When you know the attribute name, use the vertex operator.

Here is an example of reading object attributes using the vertex OPERATOR:

Var myObj = {
Prop1: "val1 ",
Prop2: "val2"
Var prop1val = myObj. prop1; // val1
Var prop2val = myObj. prop2; // val2

1.1.2. Brackets operator ( [] )

The second method for accessing objects is the brackets operator ([]). if the name of the attribute you want to access has a space, you can only use the brackets operator ([]).

This is an example of reading object attributes using the brackets operator:

Var myObj = {
"Space Name": "Kirk ",
"More Space": "Spock"
MyObj ["Space Name"]; // Kirk
MyObj ['more space']; // Spock

Tip: If the attribute name contains spaces, you must enclose the attribute name in single or double quotation marks.

Another way to use the brackets operator is to use variables to access an attribute. This method is extremely useful when you need to traverse the attribute list or Table query of an object.

Here is an example of using variables to access attributes:

Var someProp = "propName ";
Var myObj = {
PropName: "Some Value"
MyObj [someProp]; // "Some Value"

There are more:

Var myDog = "Hunter ";
Var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
Var breed = dogs [myDog]; // "Hunter"
Console. log (breed) // "Doberman"

Tip: When you access attributes using a variable name, you do not need to enclose the variable name with quotation marks. Because we actually use the value of the variable, not the name of the variable.

1.1.3. Update Object Attributes

After you create an object, you can use the dot operator or the brackets operator to update the attributes of the object.

For example, let's look at ourDog:

Var ourDog = {
"Name": "Camper ",
"Legs": 4,
"Tails": 1,
"Friends": ["everything! "]

Let's change its name to "Happy Camper". There are two ways to update the object's name attribute:

OurDog. name = "Happy Camper ";

OurDog ["name"] = "Happy Camper ";

1.1.4. Add Object Attributes

You can also add attributes to an object just like changing attributes.

Let's see how we add the "bark" attribute to ourDog:

OurDog. bark = "bow-wow ";


OurDog ["bark"] = "bow-wow ";

1.1.5. Delete Object Attributes

We can also delete the attributes of an object, for example:

Delete ourDog. bark;

1.1.6. Key-Value Pair object

The object is the same as the dictionary and can be used to store key/value pairs. If your data is the same as the object, you can use the object to find the value you want, instead of using the switch or if/else statement. This search method is extremely effective when you know that your input data is in a certain range.

This is a simple reverse alphabet:

Var alpha = {
1: "Z ",
2: "Y ",
3: "X ",
4: "W ",
24: "C ",
25: "B ",
26: ""
Alpha [2]; // "Y"
Alpha [24]; // "C"

Var value = 2;
Alpha [value]; // "Y"

1.1.7. Determine whether an attribute exists HasOwnProperty

Sometimes it is very useful to check whether an object property exists. We can use the. hasOwnProperty (propname) method to check whether the object has this property. If yes, true is returned. Otherwise, false is returned.


Var myObj = {
Top: "hat ",
Bottom: "pants"
MyObj. hasOwnProperty ("top"); // true
MyObj. hasOwnProperty ("middle"); // false

1.2. Object formatting: JSON

JavaScript Object Notation (JSON) is used to store data in the format of JavaScript objects. JSON is flexible because it allowsData StructureYesString,Number,Boolean Value,String, AndObjectAny combination.

Here is an example of a JSON object:

Var ourMusic = [
"Artist": "Daft Punk ",
"Title": "Homework ",
"Release_year": 1997,
"Formats ":[
"CD ",
"Cassette ",
"Gold": true

This is an object array, and the object has variousDetails. It also has an array of nested formarts. The appended album record can be added to the top layer of the array.

Prompt:When there are multiple JSON objects in the array, the objects must be separated by commas.

1.2.1. Access the nested attributes of a JSON object

1. Access the nested attributes of JSON objects by concatenating the dot operator or the brackets operator.

The following is a nested JSON object:

Var ourStorage = {
"Desk ":{
"Drawer": "stapler"
"Cabinet ":{
"Top drawer ":{
"Folder1": "a file ",
"Folder2": "secrets"
"Bottom drawer": "soda"
OurStorage. cabinet ["top drawer"]. folder2; // "secrets"
OurStorage. desk. drawer; // "stapler"

2. As we have seen in the previous example, JSON objects can be nested with objects and arrays. Like accessing nested objects, nested Arrays can be accessed using the brackets operator.

The following is an example of how to access nested Arrays:

Var ourPets = {
"Cats ":[
"Meowzer ",
"Fluffy ",
"Dogs ":[
"Spot ",
"Bow ",
OurPets. cats [1]; // "Fluffy"
OurPets. dogs [0]; // "Spot"

1.3. Create object for Constructor

In addition to the previous method, we can also useConstructorTo create an object.

ConstructorIt usually starts with an upper-case letter to distinguish itself from other common functions.

Below isConstructorNow:

Var Car = function (){
This. wheels = 4;
This. engines = 1;
This. seats = 1;

InConstructor, This points toConstructorCreatedObject. So when weConstructorWrite:

This. wheels = 4;

In this case, the newObjectAssign a value with the wheels attribute to 4.

You can thinkConstructorDescribes the createdObject.

1.3.1. Call object constructor

When using constructors, we use newKeywordsTo call it, as follows:

Var myCar = new Car ();

MyCar is now a CarInstance(Instance), it isConstructorIt is described as follows:

Wheels: 4,
Engines: 1,
Seats: 1

Remember: to use newKeywordsCall the constructor. Only in this way can Javascript know that this is to construct a newObjectAnd point this in the constructor to this new object.

Now, when myCarInstanceAfter the object is created, it can be used like a common object, including creating, accessing, and modifying its attributes, just like other objects. As follows:

MyCar. turboType = "twin ";

Our myCar variable now has a turboType attribute and its value is "twin ".

1.3.2. Constructors with Parameters

The constructor we previously wrote is good, but we don't want to always create the same object. What should we do?

To solve this problem, we need to add parameters to the constructor. As shown below:

Var Car = function (wheels, seats, engines ){
This. wheels = wheels;
This. seats = seats;
This. engines = engines;

Now, we can input a set of parameters when calling the constructor.

Var myCar = new Car (6, 3, 1 );

This Code uses this set of parameters to create the following objects:

Wheels: 6,
Seats: 3,
Engines: 1

Now you should try it! Modify the Car constructor so that it can assign values to the attributes of wheels, seats, and engines by using parameters.

Then, call the newly modified constructor and input three parameters. We can see that the newly created object is assigned to myCar.

2. Random Number

There are only two types of computer behavior: certainty and randomness. When you come here step by step, it is to determine the behavior. When you click a link at will, it is a random behavior.

The random number is most suitable for creating such random behavior.

2.1. Random decimal number

Math. random () is used to generate a random decimal number between 0 (including 0) and 1 (excluding 1). Therefore, Math. random () may return 0 but will never return 1.

2.2. Random integer

It is great to generate random decimals, but a more useful part of a random number is to generate a random integer.

Remember that Math. random () will never return 1. At the same time, because we are using Math. floor () to perform down rounding, we cannot get 20 results. This ensures that we get an integer between 0 and 19.

The code is similar to the following:

Math. floor (Math. random () * 20 );

We first call Math. random (), multiply the result by 20, and then pass the result from the previous step to Math. floor (), and finally get the nearest integer by rounding down.

2.3. Random Number in the specified range

The previously generated random number is between 0 and a certain number. Now the random number we want to generate is between two specified numbers.

We need to define a minimum value and a maximum value.

The following is the method we will use. Take a closer look and try to understand what the code is doing:

Math. floor (Math. random () * (max-min + 1) + min

 Finally, let's talk about the important things three times. If you think they are good, you should recommend them or comment on them. If you think they are good, you may wish to continue to improve your suggestions, your support is my greatest encouragement.


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: 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.