有两种方法可在 JavaScript 中定义数组:使用数组字面量(方括号 []);使用 Array 构造函数(new Array())。

JS 中定义数组的方法
在 JavaScript 中,定义数组有两种主要方法:
方法 1:数组字面量
使用方括号 [] 即可创建一个空数组:
<code class="js">const arr = [];</code>
使用方括号并用逗号分隔元素即可创建包含初始元素的数组:
<code class="js">const arr = [1, 2, 3, 4, 5];</code>
方法 2:Array 构造函数
使用 new Array() 创建一个空数组:
<code class="js">const arr = new Array();</code>
使用 new Array() 并提供元素作为参数创建包含初始元素的数组:
<code class="js">const arr = new Array(1, 2, 3, 4, 5);</code>
示例:
<code class="js">// 使用数组字面量 const myArray1 = [1, 2, 3, 4, 5]; // 使用 Array 构造函数 const myArray2 = new Array(1, 2, 3, 4, 5); console.log(myArray1); // [1, 2, 3, 4, 5] console.log(myArray2); // [1, 2, 3, 4, 5]</code>
以上就是js中定义数组的方法是什么的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号