The way I'd do it:
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
var array1 = ["key1", "Key2", "Key3"];
var array2 = ["Value1", "Value2", "Value3"];
var associativeArray = createAssociativeArray(array1, array2);
This (unlike your method) will return an Object, which does not have a length
property, as each of its values is not treated as an index, but rather a property. If you desperately needed to get the length of the properties of an object, you could do something like this:
function getObjectPropertiesLength(obj) {
var propNum = 0;
for(prop in obj) {
if(obj.hasOwnProperty(prop)) propNum++;
}
return propNum;
}
var values = getObjectPropertiesLength(associativeArray);
Note that if you add functions to an object, these will be treated as properties of the object and thus will contribute to the object's properties length.
What your method does:
The reason your method fails is that you're adding properties to an Array object. Yes, arrays are technically objects in Javascript, which means you can assign properties to them. This isn't using arrays in the way they are intended, though, which can have unexpected results. One of those results is that the length
value will suddenly fail to work.
This is because Array objects expect to have their properties indexed with numbers. If you assign a property to an object with a string, the function that returns the Array's length effectively can't see that property, so it won't contribute to the length of the array.