JavaScript object enumeration, class array learning (4)

Object enumeration

For in
When we traverse an array, we can have the length method to know the length of the array, and then set the upper limit of the loop to traverse, but the object does not have a length method, we can only use the for in method to traverse:

obj={
    
    
	work:student,
	name = "xxx",
	sex="male",
	proe:123,
}
for (var x in obj){
    
    
	console.log(x);
}

The result of the program will output work, name, sex, and proe in turn; when we want to get the attribute values ​​in turn, the first thing that comes to mind will be:

for (var x in obj){
    
    
	console.log(obj.x);
}

But the result will exceed our expectations, he will output four undefined, why is this?
What we need to know is obj.x------>obj['x'] , these two grammars are equal, when we each object. Property, the program will help us to do such an implicit conversion . So in the program, it will think that we are looking for the x property in the obj object, and if it doesn't, it will output undefined. This is a mistake that novices often make. We only need to change the code as follows:

for (var x in obj){
    
    
	console.log(obj[x]);
}

In this way, x will be used as a variable instead of being implicitly converted to a string.

hasOwnProperty

This method is used to determine all the attributes/methods defined by itself , and the return value is Boolean internal type

对象.hasOwnProperty("属性值/方法")

As long as it is defined by itself, it will return true, even if we define it in this way: define Object.prototype.abc=123;the attribute in its top-level prototype, when we judge it, it will still return true to us, but when we want to judge the top-level prototype The toString() method in, since it is automatically defined by the system, it will return true.

in

ABC in A

This method is similar to the previous method. It is also used to determine whether a certain property or method exists in the object, but the difference is that its search range is in the entire prototype chain , whether it is defined by ourselves or not, as long as it exists, he Will return true.

instanceof

This method is used to determine whether there is a prototype of B in the prototype chain of A.

A instanceof B;

We can use this method to judge the difference between objects and arrays. [] instanceof Array returns true, while {} instanceof Array returns false.

arguments.callee

The callee method is defined on the arguments object to determine the reference of the function. When some immediate execution function needs to use recursion, it is found that it does not have a function name, so we will use this method:

//递归计算100的阶乘
var test = (
	function (n){
    
    
	if (n === 1)
		return;
	else
		return n * arguments.callee(n-1);
}(100))

fun.caller

Returning the current calling environment is mainly to distinguish the difference between it and the callee method. One returns the current environment and the other returns a function reference.

clone

Cloning can also be called copying. To completely copy an object to another object, we can use functions to traverse the original object, and then use the new object to receive the properties of the original object one by one. If the properties are in the original Type, we copy only the data of the surface layer, but when the attribute is a reference value, we will copy the address of the reference value. When we modify the original attribute, the corresponding attribute of the copied object will also be affected, so we To do further optimized cloning, write the following function to solve the above problems:

obj={
    
    
	name:"xxx,
	a:1,
	b:[1,2,3,4],
	c:{
    
    
		c1:1,
		c3:3,
		c2:2
	}
};
obj1={
    
    };

function Clone(target,origin){
    
    
	var target = target || {
    
    };
	var toStr = Object.prototype.toString();
	var strRes = "[Object,Array]";
	for (var proe in origin){
    
    
		if(origin.hasOwnProperty(proe)){
    
    
			if(typeof(origin[proe]) !== 'null' && typeof(origin[proe]) == 'Object'){
    
    
				if(toStr.call(origin[proe] == strRes)){
    
    
					target[proe] = [];
				}
				else{
    
    
					target[proe] = {
    
    };
				}
				Clone(origin[proe],target[proe]);
			}
			else{
    
    
				target[proe] = origin[proe];
			}
		}
	}
	return target;
}

obj and obj1 represent the cloned and cloned objects, respectively. The Clone function mainly completes the following functions:

  • If the user has not passed the object to be cloned, use {} instead,
  • Determine the custom properties of the cloned object and traverse one by one
  • Use typeof to determine whether the current attribute is the original endotype, and make the corresponding steps
  • Judge the specific endotype of the reference endotype, and recursively clone again according to different results.
    In this way, the cloned object will no longer be affected by the data modification of the original object.

Array

There is undefined when the array runs. When we define the array like this **a = [1, 2, 3,,, 4]**, he will automatically fill in the vacant value to undefined instead of reporting an error, and the array runs out of bounds. It will also return undefined. The inspection of arrays in js is still relatively loose. Generally, no error will be reported. There are two ways to define it, one is a literal expression, and the other is to create an array object to define. In general, the former is mostly .
Here are several methods about arrays:

Change the original array

  • push method
    This method can add t elements to the end of the original array, and there is no limit to the number of additions.
Array.prototype.push = function (target){
    
    
	this[this.length] = target;
	this,length++;
}

The above code is the push method in the Array prototype. The underlying foundation helps us understand how to change the attribute value in the class array

  • pop method
    This method can remove the last element from the original array.

  • unshift method
    This method can add elements in sequence at the top of the original array, and the number of additions is unlimited.

  • shift method
    This method can remove the first element from the original array.

  • reverse method
    This method can reverse the original array.

  • splice method
    This method is used to cut the array, and negative numbers represent the reciprocal elements. Up to three parameters can be selected,

    • The first parameter: select the starting element for cutting
    • The second parameter: select the number of cuts
    • The third parameter: select the filling value after cutting
  • The sort method
    is used to sort the array, but if you simply call it with the array name.sort() method, the result may be different from what we imagined. It will sort by character encoding, but the sort method allows We pass a function to customize and sort according to our ideas, the specific syntax is as follows:

a = [1,4,-3,4,6,7,2,4,5];
a.sort(
	//当返回值为正数的时候,保持位序不变
	//当返回值为负数的时候,交换两数的位置
	//当返回值为0的时候,保持位序不变
	function (a,b) {
    
    
		if(a < b){
    
    
			return 1;
		}
		else{
    
    
			return -1;
		}
	}
)

In the above code, we define a positive sorting method. From the comments, we can know how to sort, which can be judged according to the return value defined by ourselves. The inside of sort is equivalent to the bubble sorting algorithm, which is called step by step. This function is passed to make judgments. Of course, the code has some parts that can be simplified. We can directly change the function body return a-b;so that the array can still be sorted in positive order, otherwise it will be sorted in reverse order.

  • Sharing a small exercise on demand
    If we need an array to be displayed in out-of-order order every time, how to use the sort method to achieve it?
    • In fact, we can use random random number and sort together to use the Math.random()method to return a number in the range of (0, 1) each time, so we let it subtract 0.5, then the return value may be negative or positive. Using it as the return value of the sort parameter function can meet our needs.

Do not change the original array

  • concat method
    This method is used to connect two arrays and return the result without modifying the original array.
  • join method
    This method is used to connect arrays with formal parameter values ​​and convert them into strings for return
  • toString method
    This method is used to convert the array into a string and return it.
  • slice method
    This method is used to intercept array elements, up to two parameters, from the start position to the end position of the interception, if there is only one parameter, the default is to intercept from this position to the last one. Negative numbers represent reciprocal elements

Array-like

An object that is very similar to an array, such as the well-known argument, stores our actual parameters like an array, but it does not have all the methods that the array has, so we call it an array-like.

var obj = {
    
    
 
                "0" : 'a',
 
                "1" : 'b',
 
                "2" : 'c',
 
                "length" : 3,
 
                "push" : Array.prototype.push
 
            }

In this way, we take the initiative to add the length property and push method that the array has to make it more like an array, and then we can call his push method. Before that, we need to understand the essence of the push method. In order to understand how to push the attribute of the class array, we have mentioned before, it is added according to the value of the length attribute. He added a "3":'d' after the "2", and the lenngth also became four. These are things that an object cannot have.
The class array must have several components: the
best four components of the class array

  • The attribute must be an index (number) attribute
  • Must have length attribute
  • It's better to add the push method
  • “splice” : Array.prototype.splice

Share a small exercise for Alibaba interview

28var obj = {
    
    
 
                "2" : 'a',
 
                "3" : 'b',
 
                "length" : 2,
 
                "push" : Array.prototype.push,
 
            }
 
            obj.push(obj);

this.length is equal to 2, so replace a with c, and length is equal to 3. The second time this.length is equal to 2, change d to d, and length+1 becomes 4.

var obj = {
    
    
 
                "2" : 'c',
 
                "3" : 'd',
 
                "length" : 2,
 
                "push" : Array.prototype.push,
 
            }

Share an array de-duplication method

The main idea is to use the object that cannot have the same name attribute, read the value from the array in turn, and then go to the object to determine whether it contains the attribute, if not, define it, if it does, it means that the array has a heavy value, which can be filtered out.

Array.prototype.unique=function () {
    
    
	var len = this.length,obj = {
    
    },arr = [];
	for(var i = 0;i < len;i++){
    
    
		if(!obj[this[i]]){
    
    
			obj[this[i]] = "xxx";//这里属性值可随意填写
			arr.push(this[i]);
		}
	}
	return arr;
}

When the method is not defined in the object, it returns undefined, if it is not, it is true, and then it is stored. The property value can be written to any value except 0, because when the property value is read, it returns 0, and the judgment is still true. , So there may be access errors.

Guess you like

Origin blog.csdn.net/baldicoot_/article/details/106237399