English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Daily Learning: Arrays and Objects Part

Object part 

Object type 

Object is an unordered collection that can store objects of any type, and all other objects inherit from this object. 

There are two ways to create an Object type: one is to use the new operator, and the other is literal notation. 

1. Using the new operator to create Object
 var obj = new Object();//Note the capitalization, and it can also be written directly as Object()
Note that the new object generated by the new Object() syntax is equivalent to the literal notation obj = {}. 

2. Using literal notation to create:

 var obj = {
 name : 'trigkit4',
 age : 21
;//It is better to add a semicolon 

When using literal notation to declare an Object object, the Object() constructor function is not called (except for FF) 

Object.prototype object 

All constructor functions have a prototype property that points to a prototype object.

Object.prototype.print = function(){ console.log(this)};
var obj = new Object();
obj.print() // Object 

The instance obj directly inherits the properties and methods of Object.prototype
1.Objects are a special type of data. Objects have properties and methods. JavaScript is an object-oriented language, but JavaScript does not use classes. JavaScript is based on [prototype][1], rather than class-based.

2.Properties: are variables belonging to a specific object. Methods: are functions that can only be called by a specific object.

3.js objects are a collection of properties and methods. A method is a function that is a member of the object. A property is a value or a set of values (in the form of an array or object), which is also a member of the object.

4.js objects are based on constructor functions, and when a new object is created using a constructor function, it can be said that a new object has been instantiated. Properties are variables inside the constructor function.
Objects instantiated using constructor functions:
 cat = new Animal();
Javascript is an object-based (object-Based on an object-oriented (OOP) language, everything you encounter is almost an object. However, it is not a true object-oriented programming (OOP) language because it does not have classes (class) in its syntax.

 <script type="text/<script type="text
 //Object is named/Collection of value pairs
  var browser = {  //Objects are enclosed in curly braces
   name:"Firefox",
   kernel:"Gecko"
  ;
</<script> 
//Access object properties through the dot (.) or '[]' operator
 browser.name   //"Firefox"
 browser["kernel"] //"Gecko" 

Object (objct) is a collection of properties, each property is composed of a 'name/The 'value pair' constitutes, js also defines a special object called 'array', which is an ordered collection of numbered values. 

js also defines a special object called 'function', which is an object with associated executable code, and code is executed by calling the function and returning the result of the operation. 

JavaScript does not have classes, but it takes a new name called 'prototype object', so 'class == prototype object', see: Writing JavaScript classes (Part 1) 

Second, the difference and relationship between class (prototype object) and object (instance)
1.Class (prototype object) is abstract and conceptual, representing a category of things.
2.Object is concrete and actual, representing a specific thing.
3.Class (prototype object) is a template for object instances, and object instances are individuals of a class.
A common misconception is that the literal value (literal) of a number is not an object. This is because of a mistake in the JavaScript parser, which tries to parse the dot operator as part of the literal value of a floating-point number. 

There are many workaround methods to make the literal value of a number look like an object.
2..toString(); // The second period can be normally parsed
2 .toString(); // Note the space before the period
(2).toString(); // 2Is calculated first

Delete property 

The only way to delete a property is to use the delete operator; setting a property to undefined or null does not truly delete the property, but only removes the association between the property and the value. 

The three major features of JavaScript object-oriented 

Encapsulation: Without considering the internal implementation, only considering the functional use
Inheritance: Inheriting new objects from existing objects
Polymorphism: So-called polymorphism refers to multiple states of a reference under different circumstances,

1.Encapsulation 

Encapsulation is to gather the common characteristics of things of the same category (including attributes and behaviors) into a class for easy use. For example, the person can be encapsulated in the following way: 

Person {
 Age (the first attribute)
Height (the second attribute)
Gender (the third attribute)

Doing things (the first behavior)
Walking (the second behavior)
Speaking (the third behavior)
} 

The benefits of encapsulation: 

Encapsulation protects the integrity of internal data;
Encapsulation makes object refactoring easier;
Weakens the coupling between modules, improves the reusability of objects;
Helps to avoid naming conflicts;

See the following example:

 <script type="text/<script type="text 
   var boy = {}; //Create an empty object
     boy.name = "Xiao Ming";//Assign values according to the prototype object's properties
     boy.age = 12;
   Create an empty object
     girl.name = "Xiao Hong";
     girl.age = 10;
 </<script> 

This is the simplest encapsulation, encapsulating two properties in an object. However, this style has two drawbacks: first, if you generate several instances, it is very麻烦 to write; second, there is no way to see what kind of relationship there is between the instances and the prototype. 

Constructor pattern 

To solve the problem of generating instances from the prototype object, Javascript provides a constructor (Constructor) pattern. 

"Constructor" is actually a common function, but it uses the this variable internally. Using the new operator on a constructor can generate an instance, and the this variable will be bound to the instance object. 

For example, the prototype objects of boy and girl can be written as follows:

 <script type="text/<script type="text 
  function Person(name, age) {
    this.name = name;
    this.age = age;
  }
</<script> 

Now we can generate instance objects.

 <script type="text/<script type="text 
  var boy = new Person("小明",12);
  var girl = new Person("小红",10);
  alert(boy.name); //Xiao Ming
  alert(boy.age); //12
</<script> 

At this point, boy and girl will automatically have a constructor property that points to their constructor.

alert(boy.constructor == Person); //true

alert(girl.constructor); //Output the entire constructor code, try it yourself.
The Prototype pattern in Javascript specifies that every constructor has a prototype property that points to another object. All properties and methods of this object will be inherited by the instances of the constructor. 

This means that we can directly define those unchanging properties and methods on the prototype object.

<script type="text/<script type="text
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.type = "Human";
Person.prototype.eat = function() {
  alert("Eat rice");
}
</<script> 

Then, generate an instance:

 <script type="text/<script type="text
var boy = new Person("小明", ""12");
var girl = new Person("小红", ""10");
alert(boy.type);//Human
boy.eat();//Eat
</<script> 

At this time, all instances' type properties and eat() methods are actually the same memory address, pointing to the prototype object, thereby improving the running efficiency.
 alert(boy.eat == girl.eat); //true
Prototype properties are an intrinsic property that specifies the constructor function that an object extends.
 The following code adds a new property size to the Animal constructor function, which is a prototype property of the cat object. By using prototype properties, all objects that extend the Animal constructor function can access the size property

cat = new Animal("feline","meow", "walk/run");
cat.prototype.size = "fat"; 

In this case, all the size properties of the Animal objects are 'fat'. The prototype is a new instance of Object by default, since it is still an object, new properties can be added to it. Just like style is an object in JavaScript, you can also add properties to the end of style.

 <script type="text/<script type="text
  /*Define a Person class*/
  function Person(_name,_age,_salary){
   //The public properties of the Person class, the definition method of the public properties of the class is: ”this.属性名“
   this.Name=_name;
   //The private properties of the Person class, the definition method of the private properties of the class is: ”var 属性名“
   var Age=_age;
   var Salary=_salary;
   //Define the public method (privileged method) of the Person class, the definition method of the public method of the class
is: ”this.functionName=function(){.....}“
   this.Show=function(){
 alert("Age="+Age+"\t"+"Salary="+Salary);//It is allowed to access a class's private properties within a public method.
   }
</<script> 

When an object looks up a property, it will first traverse its own properties. If it does not find it, it will continue to look up the object referenced by [[Prototype]]. If it still does not find it, it will continue to look up the object referenced by [[Prototype]].[[Prototype]], and so on, until [[Prototype]].….[[Prototype]] is undefined (the [[Prototype]] of Object is undefined). 

In simple terms, it is to save a reference to another object through the [[Prototype]] of the object, and to search for properties through this reference upwards, which is the prototype chain. 

null object 

The role of assigning null to a variable in JavaScript is:
Assigning an empty pointer makes it easy to understand that the variable is intended to store an object. It also facilitates debugging 

The global window object 

Any global function or variable in JavaScript is a property of window.
The self object is completely the same as the window object, and self is usually used to confirm that it is within the current window. 

The main objects of window mainly include the following ones:
 JavaScript document object
JavaScript frames object
JavaScript history object
JavaScript location object
JavaScript navigator object
JavaScript screen object

Several commonly used methods
 The valueof() method returns the original value of the specified object
The split() method splits a string into a string array and returns this array.
The indexOf() method can return the first occurrence position of a specified string value in a string.   
The substring() method is used to extract characters between two specified indices in a string.
The substr() method extracts a specified number of characters starting from the startPos position in a string.   
The join() method is used to put all elements of an array into a single string.
arrayObject.join(separator)
The reverse() method is used to reverse the order of elements in an array.   
The slice() method can return selected elements from an existing array.

Object literals 

Object literals are used to create a process that contains a large number of properties, as shown below:

 <script type="text/<script type="text
 var company = {
  name : "Microsoft",
  ages : 39,
  employees : 99000,
  CEO: "Nadella"
 ;  
</<script> 

It is necessary to note that properties and property values are separated by colons (:); multiple properties are separated by commas (,). Object literals can also define methods, simply by writing 'function' on the properties of the object, which is an anonymous function, and you can call it by writing its method name() only.

 <script type="text/<script type="text
var dog = {
 name:"husky",
 age:2,
 run:function(){
    return "123";
}
}
alert(dog.run());//If the input is dog.run, then the code of the function part behind it will pop up
</<script> 

Primitive value type wrappers 

JavaScript has five basic value types: number, string, Boolean, null, and undefined. In addition to null and undefined, the other three have so-called primitive wrapper objects. Wrapper objects can be created using the built-in constructors Number(), String(), and Boolean().

 var num = new Number(10);
console.log(typeof num);//object 
Object() method
 Object(); // Returns an empty object
Object(undefined); // Returns an empty object
Object(null); // Returns an empty object
Object(1) // Equivalent to new Number(1)
Object('foo'); // Equivalent to new String('foo')
Object(true); // Equivalent to new Boolean(true)
Object([]); // Returns the original array
Object({}); // Returns the original object
Object(function(){}); // Returns the original function 

Array part 

1.Array object 

Array object: Provides support for creating arrays of any data type.
arrayObj = new Array()
arrayObj = new Array([size])
arrayObj = new Array([element0[, element1[, ...[, elementN]]]])

Definition: var arr = [2,3,45,6]; var arr = new Array(2,4,5,7) 

There is no difference in definition between the two, [] has higher performance because the code is shorter. 

Using array and object literals: var aTest = []; Using array literals is a good choice when creating arrays; similarly, object literals can also be used to save space. The following two lines are equal, but the one using object literals is more concise:

 var oTest = new Object; //Try not to use
 var oTest = { }; //The best choice, or var 0Test = [ ]; 

Traversal To achieve the best performance in array traversal, it is recommended to use the classic for loop.

 var list = [1, 2, 3, 4, 5, ...... 100000000];
for(var i = 0, l = list.length; i < l; i++) {
 console.log(list[i]);
} 

There is a handling in the above code, that is, caching the length of the array through l = list.length. 

Array constructor 

Since the Array constructor is somewhat ambiguous in how it handles parameters, it is always recommended to use the array literal syntax - [] - to create an array. 

Therefore, the following code may be very confusing:
 new Array(3, 4, 5); // Result: [3, 4, 5]
new Array(3) // Result: [], the length of this array is 3
It is recommended to avoid using the array constructor to create new arrays. It is recommended to use the array literal syntax. They are shorter and more concise, thus increasing the readability of the code. 

Array arrays have properties 

Array arrays3Three properties: length property, prototype property, constructor property 

1.length property 

The Length property represents the length of the array, that is, the number of elements in it. Because the index of an array always starts from 0, the upper and lower limits of an array are: 0 and length-1Differently from most other languages, the length property of JavaScript arrays is mutable, which needs to be paid special attention to. 

2.prototype property 

Returns a reference to the prototype of the object type. The prototype property is shared by all objects. 

The use of the prototype property in Array array objects is illustrated by the following example.
 To add a method to the array object that returns the maximum element value in the array, declare a function, add it to Array.prototype, and use it.

 function array_max() 
{ 
var i,max=this[0]; 
for(i=1;i<this.length;i++) 
{ 
if(max<this[i]) 
max=this[i]; 
} 
return max; 
} 
Array.prototype.max=array_max; 
var x=new Array(1,2,3,4,5,6); 
var y=x.max(); 

After the code execution, y saves the maximum value in the array x, or to say6. 

3.constructor property 

Represents a function to create an object. Note: The constructor property is a member of all objects that have a prototype. They include all JScript intrinsic objects except Global and Math objects. The constructor property saves a reference to the function that constructs a specific object instance. 

For example:

 x = new String("Hi"); 
if(x.constructor==String) //to be processed (condition is true). 
//or 
function MyFunc{ 
//Function body. 
} 
y=new MyFunc; 

if(y.constructor==MyFunc)//to be processed (condition is true).
For arrays:
 y = new Array();

Array Object Method

sort() method 

Syntax
arrayObject.sort(sortby)
sortby optional. Specifies the sorting order. Must be a function.
var arr = [11,2,28,4,5,1});
console.log(arr.sort());//return [1, 11, 2, 28, 4, 5]
Why here11,28Why is it not sorted in order? Because the sort without parameters is sorted according to the character encoding order. 

How to sort the array elements in ascending order? See the following code:

 var arr = [11,2,28,4,5,1});
 console.log(arr.sort(function(a,b){
  return a-b;//return [1, 2, 4, 5, 11, 28]
 }); 

If you want to sort by other criteria, you need to provide a comparison function, which compares two values and then returns a number to indicate the relative order of the two values. The comparison function should have two parameters a and b, and the return value should be as follows:
 If a is less than b, and a should appear before b in the sorted array, return a value less than 0.
If a is equal to b, return 0.
If a is greater than b, return a value greater than 0.

That's all for this article, I hope it helps with your learning, and I also hope everyone will support the Yelling Tutorial more.

You May Also Like