javascript - 使用数字和字符串创建新的 Array() 构造函数

标签 javascript arrays

实际上,我正在为其他人编写代码。

在解决我发现的错误时 诸如此类。

注意:API 给出的是数字类型的产品编号。

Sometimes passing only one productNumber in new Array(). then a new bug occurs.

And when entering productNumber more than one then working fine.

Why arr1[0] is giving undefined.

var productNumber1 = 1001;
var arr1 = new Array(productNumber1);
console.log("arr1",arr1[0]);

var productNumber2 = '1001';
var arr2 = new Array(productNumber2);
console.log("arr2",arr2[0]);

能否请人解释一下这种行为。

最佳答案

在 case1 中,您传递的参数被视为数组的长度

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.

arrayLength

If the only argument passed to the Array constructor is an integer between 0 and 2^32-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.

所以实际上在案例 1 中,您正在创建一个长度为 1001 的数组。

但是在情况 2 中,它被视为一个元素,因为它不是数字。

关于javascript - 使用数字和字符串创建新的 Array() 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46884680/

相关文章:

javascript - 如何将 DocumentFragment 居中对齐?

javascript - Netsuite Script beforeLoad 记录未被修改

JavaScript语法错误: uncaught expression

javascript - 无法使用 Array.from 将 FileList 转换为 Array 并在 typescript 中传播语法

python - 使用 NumPy argsort 并接收二维数组

javascript - React Class如何在同一文件中的所有方法中传递变量

javascript - 如何在使用 ASP.NET MVC 核心制作的应用程序的一两个页面中使用 Angular 4 作为迷你水疗中心?

c - 使用 fgets() 的段错误

java 两个线程操作同一个数组

javascript - React this.props 不更新