سؤال

I've been searching for hours for an error in my javascript's code but I really don't understand why this error occur.

So I have 2 array that I've get by using ajax and I want to merge them into an 2d array but this error happen :

Uncaught TypeError: Cannot set property '0' of undefined

So this is my code :

var arrayCityAccident = new Array([]);

for(var i = 0; i < responseAccident.length; i++)
{
arrayCityAccident [i][0] = responseCity[i]['city'];
arrayCityAccident [i][1] = responseAccident[i];
}

I've look up to see if my both 1d array have values and yes they have values so if someone could help me it will help me a lot.

Thank you in advance !

هل كانت مفيدة؟

المحلول

You need to add a new array to arrayCityAccident for each index i:

var arrayCityAccident = [];

for(var i = 0; i < responseAccident.length; i++)
{
    arrayCityAccident.push([responseCity[i]['city'], responseAccident[i]]);
}

نصائح أخرى

Well, as soon as i becomes bigger than 0 in your loop, arrayCityAccident[i] doesn't return an array anymore. You only defined arrayCityAccident[0], so accessing arrayCityAccident[i][0] isn't possible.

Just add another array to arrayCityAccident before defining its elements:

var arrayCityAccident = new Array([]);

for(var i = 0; i < responseAccident.length; i++)
{
    arrayCityAccident[i] = []; // add a new array to arrayAccident
    arrayCityAccident[i][0] = responseCity[i]['city']; // now you can set those properties
    arrayCityAccident[i][1] = responseAccident[i];     // without problems
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top