javascript - How do you declare an array using an initializer list in javascript?
问题描述
creating the array would be this:
final int SIZE = 15, MULTIPLE = 10;
int [] list = new int [SIZE];
however, would this be the correct way to initialize the array?
for (int index = 0; index < SIZE; index++)
list [index] = index * MULTIPLE;
解决方案
Javascript 很奇怪(标准 js)。您可以初始化一个新数组,使用new Array(10)
它创建一个长度为 10 但具有空值的新数组。因此,您不能迭代或映射数组或使用这些值。
数组上有一个.fill
函数,如果将其与 Array(10) 结合使用,则会创建一个带有值的具有一定长度的数组。
然后,您可以使用for
或更多 javascript 惯用的为什么map
将索引值与您的乘数进行映射。
const SIZE = 15, MULTIPLE = 10;
const tmpArray = new Array(SIZE)
const initalArray = tmpArray.fill(0).map((value, i) => (i * MULTIPLE))
console.log(initalArray)
推荐阅读
- java - 不使用正则表达式将字符串转换为地图
- javascript - useEffect 在它之外读取数组
- android - 如何平滑列表项在特定位置的移动
- excel - Excel VBA中的多列动态过滤
- c# - C#如何获取鼠标在上方的表单中的元素
- python - 使用 Owlready2 在 OWL/RDF 本体中检索 rdf 标签
- docker - 使用 Docker Compose 在 Linux 容器上挂载 Windows 网络共享
- anaconda - .zshrc 文件中的环境变量读取不正确
- getstream-io - 如何在我的项目中集成 strem-chat?
- xml - 使用 XSL 和自结束标记转换 XML