I need an array with the boolean values, but instead, it gives me the variable name.
Here is a simplistic example:
I declare variable to check for match to other data, gives boolean results.
var usatest = new RegExp("USA").test(continent); //this gives true result
var canadatest = new RegExp("Canada").test(continent); //this gives false result
var mexicotest = new RegExp("Mexico").test(continent); //this gives false result
create array from the variables:
var testArray = 'usatest,canadatest,mexicotest'.split(",");
so testArray is ['usatest','canadatest','mexicotest']
but want [ true, false, false ]
tested other ways:
var testArray1 = [{}];
testArray1[0] = usatest;
testArray1[1] = canadatest;
testArray1[2] = mexicotest;
result is array [ true , false, false]
.
So try to substitute the name with the array value (would allow me to use a for loop for a long list)
var testArray2 - [{}];
testArray2[0] = usatest;
testArray2[1] = testArray1[1];
testArray2[2] = testArray1[2];
would expect to get [ true, false, false]
but get [true , 'canadatest', 'mexicotest']
why does using testArray1[1]
in the second array return the variable name and not the boolean value? And maybe that will answer why testArray
does not return boolean values either. What am I missing?
Thanks,
Doc
2
Answers
For your first attempt,
testArray
is the result of aString.split
operation, so of course it’s an array ofstrings
.For your third attempt: Are you sure you used the correct array to get your data from, because
testArray1[1]
is a boolean, there is no way, thattestArray1[1]
will give youcanadatest
The simplest in your usecase is possibly (assuming
continent
is defined accordingly)Ie, create an array from the results of the
RegExp.test
function directly …Dynamically access to variables (ie when their name is stored in another variable) is a real pain in JS, especially if they are not living in the global
window
context.I think you can correct this step
create an array from the variables: