Avoid using eval() as it is considered harmful. Instead of using eval, pass the array as an argument to a function that can determine its length based on the argument name. This simple approach will solve the problem without relying on unsafe practices.
var a1 = [0,1,2,3,4,5];
var a2 = [0,1,2,3];
var a3 = [0,1,];
function getArrayLength(a){
return a.length;
}
getArrayLength(a1);
getArrayLength(a2);
getArrayLength(a3);
Check out this code snippet for a better solution.
In your original code, the issue lies in writing: eval([arrayname]).length
. The correct way to access the length of an array using eval is: eval(arrayname).length
, which evaluates the string as an object reference and retrieves the length of its members.
The following example demonstrates how the incorrect eval version could potentially be used, but remember to avoid using eval for real scenarios:
var problem_0 = ["a","b","c","d"];
arrayStringName = "problem_0";
arrayObjectName = eval(arrayStringName);
arraylength = arrayObjectName.length;
for (i = 0; i < arraylength; i++) {
alert(arrayObjectName[i]);
}
Explore this link for a demonstration.