How to create an array in JavaScript?

      How to create an array in front-end JavaScript? We can do this in the following ways:

     1. Create an array using Array Literals:

  The simplest way is to use square brackets [] to define an array, and then add elements inside the square brackets, separating each element with a comma.

var fruits = ["苹果", "香蕉", "橙子"];

  This will create an array fruits containing three string elements.

  2. Create an array using the constructor:

  You can use the array constructor Array() to create a new empty array, or an array with initial elements.

var emptyArray = new Array();
var numbers = new Array(1, 2, 3, 4, 5);

  This will create an empty array emptyArray and an array numbers containing numeric elements.

  3. Add elements using array index:

  Arrays can be created and initialized by specifying array indexes.

var myArray = [];
myArray[0] = "第一个元素";
myArray[1] = "第二个元素";
myArray[2] = "第三个元素";

  This creates an array myArray containing three string elements.

  4. Use the Array.from() method to create an array:

  The Array.from() method allows us to create new arrays from similar arrays or iterable objects such as Strings, Sets, Maps, etc.

var str = "Hello";
var charArray = Array.from(str);

  This will create a charArray containing each character in the string.

  5. Use the spread operator (Spread Operator):

  The spread operator allows us to create a new array from an existing array.

var numbers = [1, 2, 3];
var newNumbers = [...numbers, 4, 5];

  This will create a new array newNumbers containing the old array elements and the new elements.

  Regardless of which method is used, elements can be added to, modified, or removed from the array as needed to meet your specific programming needs. Arrays are very important data structures in JavaScript, used to store and process large amounts of data. Hopefully these examples help us better understand how to create arrays.

Guess you like

Origin blog.csdn.net/zy1992As/article/details/132690759