I'm working on a function that takes two arrays of numbers as its arguments. I use a ternary operator to determine if both arrays are of the same length or not. If not, I run an if condition loop to determine which is longer and set the name of the argument as the property of a variable named longer so I can access the element with the most items without knowing which it is beforehand. Here's a sample.
someFunc(numListA, numListB){
let isEqual = (numListA.length == numListB.length) ? true : false;
let longer = '',
shorter = '',
difference = [longer].length - [shorter].length,
appendNums = [];
if(!isEqual){
if(numListA.length > numListB.length){
longer = 'numListA'; shorter = 'numListB';
}
else{ longer = 'numListB'; shorter = 'numListA'; }
appendNums = [...[longer].splice([longer].length-difference-1, [longer].length)];
}
........
}
When console.log()ing the appendNums variable it returns the text in the longer variable as a string rather than plugging the variable in place as something I can access.
What I want this part of the function to do is to determine the difference in the length between the two arrays and take the trailing entries of, whichever, the longest and store them in the appendNums variable. The only thing I could think to do was trying backticks instead of quotes to make them template literals but it still had the same result. How can I get the bracket notation to plug in the variable name so it can be accessed?
longer = 'numListA'should belonger = numListAsame applicable forshorteralso[longer].lengtheven before you have determinedlonger(at this point,longer&shorterboth are empty strings.)[variableName]will return whatever isassigned to variable whose name is stored invariableName. This is not true though: e.g.[longer]in the 7th line evaluates to the singleton array['']instead of the array assigned to the variable whose name matches the value oflonger. Generally, you cannot access the scope of a function reflectively without usingeval. There is no need to do that either if you follow the suggestion by @JavascriptLover-SKT .