Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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

like image 808
devneeddev Avatar asked Jan 28 '26 13:01

devneeddev


2 Answers

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 }, () => []);
like image 63
CertainPerformance Avatar answered Jan 31 '26 03:01

CertainPerformance


Using ES6 you can:

let [photos, tags] = [[], []];
like image 34
omri_saadon Avatar answered Jan 31 '26 01:01

omri_saadon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!