Js method of changing the original array and an array of solutions to change the original

Change the original array method

  • pop (): Delete the last element of the array, and returns that element
  • After addition array length in the end of the array element, and returns the updated: push ()
  • shift (): Removes the first element of the array, and returns that element
  • Array length after the first add elements in the array, and returns updated: unshift ()
  • sort (): Sort of an array (ASCII character carried out by sorting), callback functions can be added according to the rules you want to sort
  • reverse (): Array Reverse
  • splice (index, howmany, new data): returns the removed elements consisting of arrays.

Solution to change the original array

BACKGROUND: a need equal the original array and the array, and does not affect the original array when the array operation process: deep copy.

var A = [. 1, 2,. 3 ];
 // this time need b is equal to a, but b is changed, does not affect A 

// method, Slice () 
var B1 = a.slice (); 

// Method II. the concat () 
var B2 = [] .concat (A); 

// method three, the JSON.parse (the JSON.stringify ()) 
var B3 = the JSON.parse (the JSON.stringify (A)); 

// method IV, handwritten The method of deep copy 
var the deepCopy = function (obj) {
  IF ( typeof ! obj == 'Object') return ;
  var newobj obj = the instanceof the Array? []: {};
  for ( var key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    }
  }
  return newObj;
}
var b4 = deepCopy(a);

 

Guess you like

Origin www.cnblogs.com/Ingots/p/11517018.html