2

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

2
  • Can you use ES6? Commented Nov 15, 2018 at 11:29
  • Just for the sake of interpreting the error, writing: var photos,tags = new Array(); is the same as writing var photos; var tags = new Array();. Hence the error (photos is undefined). Commented Nov 15, 2018 at 11:34

2 Answers 2

8

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 }, () => []);
Sign up to request clarification or add additional context in comments.

Comments

5

Using ES6 you can:

let [photos, tags] = [[], []];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.