Collapse of arrays
Trying to delete all the values in the ARR, the array collapsed during the loop;
1. One way to do this is to fall into a pit
var arr = ["a"."b"."c"."d"];
for(var i=0; i<arr.length; i++){ arr.splice(i,1);// Delete 1 element from I
}
console.log(arr);// Is the result []? nonono.. His result is (2) [" B ", "D "]
// The array becomes ["b","c","d"] after the first element is deleted;
["b", "d"] ["b", "d"]
// I =2, but then the array is ["b", "d"], there is no 2 at all, the maximum is 1, so the loop stops.
(2) ["b", "d"];
Copy the code
- How to solve array collapse? i–
var arr = ["a"."b"."c"."d"];
for(var i=0; i<arr.length; i++){ arr.splice(i,1);// Delete 1 element from II -;// The key is always to let I loop after entering for loop again with I =0 to start again
}
console.log(arr);/ / perform []
Copy the code
Deep copy
The first way
function copyObj(obj){
var newObj = Array.isArray(obj)? [] : {};// create a new memory address
for(var key in obj){ // This loop can loop through both arrays and objects;
if(typeof obj[key] === "object"){
newObj[key] = copyObj[key];
}else{ newObj[key] = obj[key]; }}return newObj;
}
var obj = {name:"Zhang".age:20};
var arr1 = copyObj(obj);
console.log(arr1);// The object is passed in
Copy the code
The performance of the second method is not as good as the first method above
Deep copy can be done with json.stringify and json.parse
1. Json.stringify converts an object to a JSON string
2. Json. parse converts JS strings into objects
3. But JSON: some attributes, such as undefined and function, will be ignored, and these elements will be discarded after copying, resulting in inaccuracy
var obj={
name:"Zhang".age:20,}var res= JSON.stringify(obj);// Convert the obj object to a string
console.log(res);
var newObj=JSON.parse(res);// Convert the string to a new object
console.log(newObj);// It can be used for deep copy, which copies the same object as the original
Copy the code