[英]Defining arrays in single line in Javascript
I am trying to declare multiple arrays in a single line. 我试图在一行中声明多个数组。 But I am taking this error.
但是我正在犯这个错误。 (Cannot set property "0" of undefined)
(无法设置未定义的属性“ 0”)
var photos,tags = new Array();
flickrJSON.items.forEach(function(item, index) {
photos[index] = item.media.m;
tags[index] = item.tags;
});
Why I take this error? 为什么我会出现此错误? Can somebody explain?
有人可以解释吗? and How can I fix it
以及我该如何解决
You're trying to use two arrays there - an array named photos
, and an array named tags
, so you need to use new Array
(or, preferably, []
) twice : 您正在尝试使用两个数组-一个名为
photos
的数组和一个名为tags
的数组,因此您需要两次使用new Array
(最好是[]
):
var photos = [], tags = [];
In your original code, var photos,
will result in photos
being undefined
, no matter what comes after the comma. 在原始代码中,
var photos,
将导致photos
undefined
,无论逗号后面是什么。
If you wanted to create a lot of arrays at once and didn't want to repeat = []
each time, you could use Array.from
with destructuring to keep code DRY: 如果您想一次创建很多数组,并且不想每次都重复
= []
,则可以使用Array.from
进行解构以使代码保持DRY:
const [arr1, arr2, arr3, arr4, arr5] = Array.from({ length: 5 }, () => []);
使用ES6,您可以:
let [photos, tags] = [[], []];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.