JavaScript daily required array and object part, javascript Array
Object Section
Object Type
An Object is an unordered set that stores any type of objects. All other objects inherit from this Object.
There are two types of Object creation: the new operator and the literal representation.
1. Use the new operator to create an Object
Var obj = new Object (); // note the upper case, you can also directly write the Object ()
Note: The new Object is generated using the new Object () method, which is equivalent to the literal method obj =.
2. Create using the literal method:
var obj = {
name: 'trigkit4',
age: 21
}; // The semicolon is best added
When using a literal to declare an Object, the Object () constructor (except FF) will not be called
Object.prototype object
All constructors have a prototype attribute 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. The object is just a special kind 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], not class-based.
2. Attribute: is a variable that belongs to a specific object. Method: It is a function that can only be called by a specific object.
3.js object is a collection of attributes and methods. A method is a function that is a member of an object. An attribute is a value or a set of values (in the form of an array or object) and is a member of an object.
4.js object is based on the constructor function, when using the constructor function to create a new object, it can be said that a new object is instantiated. Attributes are variables inside the constructor function.
Object instantiated using the constructor function:
cat = new Animal ();
Javascript is an object-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because there is no class in its syntax.
<script type = "text / javascript">
// The object is a collection of name / value pairs
var browser = {// Objects are enclosed in curly braces
name: "Firefox",
kernel: "Gecko"
};
</ script>
// Access the properties of the object by dot (.) Or "[]"
browser.name // "Firefox"
browser ["kernel"] // "Gecko"
Object (objct) is a collection of properties (property), each property is composed of "name / value pairs", js also defines a special object-an array, which is an ordered collection of numbered values.
js also defines a special object-a function. A function is an object with executable code associated with it. The function is executed by calling the function and returns the operation result.
There is no class in JS, but it takes a new name called "prototype object", so "class == prototype object". For details, please see: JavaScript class writing (1)
Second, the difference and connection between class (prototype object) and object (instance)
1. Classes (prototype objects) are abstract, conceptual, and represent a class of things.
2. The object is specific, actual, and represents a specific thing.
3. A class (prototype object) is a template for an object instance, and an object instance is an individual of the class.
A common misconception is that literals of numbers are not objects. This is due to a bug in the JavaScript parser, which attempts to parse the dot operator as part of the floating-point numeric denomination.
There are many workarounds to make the literal value of a number look like an object.
2..toString (); // The second dot can be parsed normally
2 .toString (); // Note the space before the dot
(2) .toString (); // 2 is calculated first
Delete attribute
The only way to delete an attribute is to use the delete operator; setting the attribute to undefined or null does not actually delete the attribute, but only removes the association between the attribute and the value.
Three major features of JavaScript object-oriented
Encapsulation: Do not consider internal implementation, only consider function usage
Inheritance: inherit new objects from existing objects
Polymorphism: The so-called polymorphism refers to the multiple states of a reference in different situations,
1. Packaging
Encapsulation is to put the commonality (including attributes and behaviors) of the same category of things into one class for easy use. For example, people can use the following methods to encapsulate:
people{
Age (attribute one)
Height (attribute two)
Gender (attribute three)
Doing things (one of the acts)
Walking (Behavior 2)
Speak (Behavior 3)
}
The benefits of packaging:
Encapsulation protects the integrity of internal data;
Encapsulation makes the reconstruction of objects easier;
Weaken the coupling between modules and improve the reusability of objects;
Helps to avoid namespace conflicts;
See an example below:
<script type = "text / javascript">
var boy = {}; // Create an empty object
boy.name = "小 明"; // Assign according to the attributes of the prototype object
boy.age = 12;
var girl = {};
girl.name = "Little Red";
girl.age = 10;
</ script>
This is the simplest encapsulation, encapsulating two properties in an object. However, this writing method has two disadvantages. One is that it is very troublesome to write if a few more instances are generated. Second, there is no way between the instance and the prototype.
Constructor pattern
In order to solve the problem of generating instances from prototype objects, Javascript provides a constructor (Constructor) mode.
The so-called "constructor" is actually an ordinary function, but this variable is used internally. Use the new operator on the constructor to generate an instance, and this variable will be bound to the instance object.
For example, the prototype objects of boy and girl can now be written like this:
<script type = "text / javascript">
function Person (name, age) {
this.name = name;
this.age = age;
}
</ script>
We can now generate instance objects.
<script type = "text / javascript">
var boy = new Person ("小 明", 12);
var girl = new Person ("小红", 10);
alert (boy.name); // Xiaoming
alert (boy.age); // 12
</ script>
At this time boy and girl will automatically contain a constructor attribute, pointing to their constructor.
alert (boy.constructor == Person); // true
alert (girl.constructor); // output the entire string of constructor code, try it yourself
Prototype mode Javascript stipulates that each constructor has a prototype attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.
This means that we can define those immutable properties and methods directly on the prototype object.
<script type = "text / javascript">
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.protype.type = "Human";
Person.protype.eat = function () {
alert ("Eat rice");
}
</ script>
Then, generate an instance:
<script type = "text / javascript">
var boy = new Person ("小 明", "12");
var girl = new Person ("小红", "10");
alert (boy.type); // Human
boy.eat (); // Eating
</ script>
At this time, the type attribute and eat () method of all instances are actually the same memory address, pointing to the prototype object, so the operating efficiency is improved.
alert (boy.eat == girl.eat); // true
The prototype attribute is a built-in attribute that specifies the constructor function that the object extends.
The following code adds a new property size to the Animal constructor function. This new property is the prototype property of the cat object. By using the prototype property, 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, the size property of all Animal objects is "fat". The prototype defaults to a new instance of Object. Since it is still an object, new properties can be added to the object. Just like style is an object of javascript, you can continue to add attributes after style.
<script type = "text / javascript">
/ * Define a Person class * /
function Person (_name, _age, _salary) {
// Person class's public property, the public property of the class is defined as: "this. Property name"
this.Name = _name;
// Person class private property, the class private property is defined as: "var property name"
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
Yes: "this.functionName = function () {.....}"
this.Show = function () {
alert ("Age =" + Age + "\ t" + "Salary =" + Salary); // Access to private properties of the class in public methods is allowed
}
</ script>
When an object searches for a certain property, it will first traverse its own properties, if not, it will continue to search for the object referenced by [[Prototype]], if not, continue to search for the referenced by [[Prototype]]. [[Prototype]] Objects, and so on, until [[Prototype]] .... [[Prototype]] is undefined (Object [[Prototype]] is undefined)
Simply put, the reference to another object is saved through the [[Prototype]] of the object, and the attribute search is performed upward through this reference. This is the prototype chain.
null object
The role of js to assign a null value to a variable is:
Assigning a null pointer makes it easy to understand that this variable is intended to be used to store objects. Also easy to adjust
Global window object
Any global function or variable in JavaScript is a property of window.
The self object is exactly the same as the window object, and self is usually used to confirm that it is in the current form.
The main objects of window are as follows:
JavaScript document object
JavaScript frames object
JavaScript history object
JavaScript location object
JavaScript navigator object
JavaScript screen object
Several common methods
valueof () method: returns the original value of the specified object
The split () method splits the string into a string array and returns this array.
The indexOf () method returns the first occurrence of a specified string value in the string.
The substring () method is used to extract characters between two specified subscripts in a string.
The substr () method extracts a specified number of strings from the startPos position from the string.
The join () method is used to put all the elements in the array into a string.
arrayObject.join (separator)
The reverse () method is used to reverse the order of the elements in the array.
The slice () method returns the selected elements from the existing array.
Object literal
Object literals are used to create processes that contain a large number of attributes, as follows:
<script type = "text / javascript">
var company = {
name: "Microsoft",
ages: 39,
employees: 99000,
CEO: "Nadella"
};
</ script>
It should be noted here that attributes and attribute values are separated by a colon (:); multiple attributes are separated by a comma (,). Object literals can also define methods, just write fu on the properties of this objectnction is OK, this is an anonymous function, to call it, just write his method name ().
<script type = "text / javascript">
var dog = {
name: "husky",
age: 2,
run: function () {
return "123";
}
}
alert (dog.run ()); // If you enter dog.run, the code of the function part behind it will pop up
</ script>
Basic value type wrapper
js has five basic value types: number, string, Boolean, null, and undefined. In addition to null and undefined, the other three have so-called basic packaging objects. You can use the built-in constructors Number (), String (), and Boolean () to create wrapper objects.
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 () {}) // return to 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 the definition of the two, the performance of [] is high because the code is short.
Use array and object literals: var aTest = []; when creating an array, using array literals is a good choice; similarly, object literals can be used to save space. The following two lines are equal, but using object literals is shorter:
var oTest = new Object; // Try not to use
var oTest = {}; // The best choice, or var 0Test = [];
Traversal To achieve the best performance for traversing arrays, 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]);
}
The above code has a process that caches the length of the array through l = list.length.
Array constructor
Since the constructor of Array is a bit ambiguous in how to deal with parameters, it is always recommended to use the literal syntax of arrays-[]-to create arrays.
So the following code will be confusing:
new Array (3, 4, 5); // Result: [3, 4, 5]
new Array (3) // Result: [], the length of this array is 3
You should try to avoid using array constructors to create new arrays. It is recommended to use the literal syntax of arrays. They are shorter and more concise, thus increasing the readability of the code.
Array properties
Three properties of Array array: length property, prototype property, constructor property
1.length attribute
The Length attribute indicates 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-1. Unlike most other languages, the length property of JavaScript arrays is variable, which requires special attention.
2.prototype attribute
Returns a reference to the prototype of the object type. The prototype property is common to object.
For the Array array object, the following example illustrates the use of the prototype property.
Add a method to the array object to return the maximum element value in the array. To accomplish this, 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 is executed, y saves the maximum value in the array x, or 6.
3.constructor attribute
Represents the function that creates the object. Note: The constructor attribute is a member of all prototype objects. They include all JScript inherent objects except Global and Math objects. The constructor property holds a reference to the function that constructs a specific object instance.
E.g:
x = new String ("Hi");
if (x.constructor == String) // Process (condition is true).
// or
function MyFunc {
// Function body.
}
y = new MyFunc;
if (y.constructor == MyFunc) // Process (condition is true).
For arrays:
y = new Array ();
Array object methods
sort () method
grammar
arrayObject.sort (sortby)
sortby is optional. Specifies the sort 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 aren't Mao's 11 and 28 arranged in order? This is because sort without parameters is sorted in the order of character encoding.
So, what if you want to sort the array elements from small to large? Look at the code below:
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 that compares two values and then returns a number that explains the relative order of the two values. The comparison function should have two parameters, a and b, whose return values are as follows:
If a is less than b, a should appear before b in the sorted array, and a value less than 0 is returned.
If a is equal to b, 0 is returned.
If a is greater than b, a value greater than 0 is returned.
The above is the whole content of this article, I hope it will be helpful to everyone's learning, and I hope everyone will support the home of helpers.