I am trying to declare multiple arrays in a single line. But I am taking this error. (Cannot set property "0" of undefined)
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 :
var photos = [], tags = [];
In your original code, var photos,
will result in photos
being undefined
, no matter what comes after the comma.
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:
const [arr1, arr2, arr3, arr4, arr5] = Array.from({ length: 5 }, () => []);
使用ES6,您可以:
let [photos, tags] = [[], []];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.