当前位置:网站首页>JS create an array (literal)

JS create an array (literal)

2022-06-23 15:11:00 Liujiayi_

(1) Use literals to create arrays // grammar :[]
var arr = [];

(2) When you create an array using literals , You can specify the elements in the array at creation time

var arr = [1,2,3,4,5,10];

(3) When creating an array using a constructor , You can also add elements at the same time , The element to be added is passed as a parameter of the constructor         Use... Between elements , separate
var arr2 =new Array( 10,20,30);

console.log( arr2);

(4) Create an array with only one element 10

arr = [ 10];
(5) Create a length of 10 Array of
arr2 = new Array ( 10);
(6) The elements in the array can be any data type
arr = [ "hello",1,true,nul1,undefined];
It could be an object
arr= [{name : " The Monkey King "},{name : " The sand monk "},{name : " Pig eight quit "}];

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      arr = [{ name: " The Monkey King " }, { name: " The sand monk " }, { name: " Pig eight quit " }];
      alert(arr[1].name);
    </script>
  </body>
</html>

 (7) It can also be a function
arr = [function(){alert(1)},function(){alert(2)}];

console.log( arr);
arr[0]();

 

(8)  You can also put an array in the array , The following array is called two-dimensional array

arr = [[1,2,3],[3,4,5],[5,6,7]];

console.log( arr[1]);

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      arr = [
        [1, 2, 3],
        [3, 4, 5],
        [5, 6, 7],
      ];

      alert(arr[1]);
    </script>
  </body>
</html>

 

原网站

版权声明
本文为[Liujiayi_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231424014550.html