Js commonly used array manipulation method summary

  • 2020-03-30 03:24:40
  • OfStack

//Array splitting in javascript
var colors = ["red","green","blue"];
//alert(colors.toString());
alert(colors.join("|")); //The result is red|green|blue
var colors = ["red","green","blue",null];
alert(colors.join("|"));//red|green|blue|
//Note that when an array contains a value that is null or undefined, the result is returned as an empty string
-------------------------------------------
//Array delete and add
var colors = ["red","green","blue"];
//alert(colors.toString());
colors.push("white","test");//The result is the length of the array
alert(colors.join("|"));//The result is red | green | blue | white | test
//Add an element to the beginning of the array
var colors = ["red","green","blue","test"];
var item = colors.unshift("first");//Add an element to the beginning of the array
alert(colors.join("|"));//Returns the final array


//Remove elements
var colors = ["red","green","blue","test"];
var item = colors.pop();//Returns the result test of the deleted option
alert(colors.join("|"));//Returns the final array The results of red|green|blue
//Delete the opening element
var colors = ["red","green","blue","test"];
var item = colors.shift();//Deletes the first option of the array
alert(colors.join("|"));//Returns the final array
-------------------------------------------------
//Array order example
//Reverse order
var colors = ["red","green","blue","test"];
colors.reverse();
alert(colors);//The result: test,blue,green,red
//Sort an array
var values = [0,1,5,10,7];
values.sort(compare);
alert(values);
//document.writeln(values);

}
 function compare(value1,value2){
	if(value1<value2){
		return 1 ;
	}else if(value1>value2){
		return -1 ;
	}else return 0 ;
} 
-----------------------------------------------------
//Add the array concat() method to the array
var colors = ["color","red"];
var colors2 = colors.concat(["ccc","bbbb"],'3333',['vvccxx',['oolll','lll']]);
alert(colors2);//Returns the result is: color, red, CCC, BBBB, 3333, VVCCXX, oolll, the name 'LLL

//The slice() method copies an element in an array without breaking the previous element
var colors = ["color","red",'eeee','221111'];
var colors2 = colors.slice(1);//I'm going to start at 1
alert(colors2);//The result: red,eeee,221111

var colors = ["color","red",'eeee','221111'];
var colors2 = colors.slice(1,3);//I'm going to start at 1 To the first 3 End of position 
alert(colors2);//The result is red, eeee
---------------------------------------------------------------------
// In the array Remove elements
var a = [1,2,3,5,8];
var r = a.splice(0,2); //Delete the first two items
alert(a);//The result is 3,5,8

var a = [1,2,3,5,8];
var r = a.splice(1,1,100,200); //I'm going to start at number two and delete an item and then insert 100, 200
alert(a);// As a result, 1,100,200,3,5,8


Related articles: