1. Use array literals
var arr = []; // Create an empty array var arr1 = [10]; / / create a contains 1 item data for 10 var arr2 = array (" a ", "b", "c", "d"]. // Create an array of four stringsCopy the code
2. Use the Array constructor
Var arr1 = new Array(); Var arr2 = new Array(20); var arr2 = new Array(20); Var arr3 = new Array("a","b","c"); var arr3 = new Array("a","b","c"); Var array4 = new Array('10'); / / / "10"Copy the code
3. Array.from method to create arrays (new in ES6)
function arga(... args) { //... Args Array of remaining arguments, supplied by the actual arguments passed to the function let arg = array. from(args); console.log(arg); // ['arr1',26,'from'] } arga('arr1', 26, 'from')Copy the code
Mapping transformation
Pass a mapping function to the array.from () method as the second argument
function arga(... args) { return Array.from(args, value => value + 1); } let arr = arga('arr', 26, 'pop'); console.log(arr); //['arr1',27,'pop1']Copy the code
Pass a mapping function to the array.from () method as the third argument
const helper = { diff: 1, add(value) { return value + this.diff; Function translate() {return array. from(arguments, helper.add, helper);}} function translate() {return array. from(arguments, helper.add, helper); } let arr = translate('liu', 26, 'man'); console.log(arr); // ["liu1", 27, "man1"]Copy the code
4. Array.of method to create arrays (new in ES6)
The // array.of () method always creates an Array containing all the parameters passed in, regardless of their number or type. let arr = Array.of(1, 2); console.log(arr.length); //2 let arr1 = Array.of(3); console.log(arr1.length); //1 console.log(arr1[0]); //3 let arr2 = Array.of('2'); console.log(arr2.length); //1 console.log(arr2[0]); / / '2'Copy the code