0

I have an array that contains variables that could change position and I want to create a for loop that checks to see if a specific variable's length equals zero. I would rather not have to target the variable's position in the array, as it could change.

So, is there any way to target a variable in the array by the variable's name?

Uncle Slug
  • 853
  • 1
  • 13
  • 26
  • 1
    It would be amazingly useful to see this array and expected output. – mplungjan Apr 03 '15 at 05:45
  • My question is pretty straight forward, and I'm not looking for help with the output. I didn't think it was necessary to show code for something that might not be possible. – Uncle Slug Apr 03 '15 at 05:49
  • Arrays don't contain variables, they have properties that contain values. Posting some code (even not working code or pseudo code) will help in deciphering what you are trying to achieve. – RobG Apr 03 '15 at 05:55
  • Also not knowing your grasp of JS, your Array might be our JS Object or vice versa. – mplungjan Apr 03 '15 at 06:05

4 Answers4

1

Arrays normally store their data under number indexes like 0 1, 2, n so no. Store your variables in an Object using keys and access your vars using that keys with something like:

var data = {varName: var1, varName2: var2};
data['varName'] = //do your thing
DSF
  • 804
  • 7
  • 15
1

A dictionary is what you want.

var myDict = {x:"firstVariable", y:"second", z: ""}
 //check length
 for (key in myDict.keys()) {
     if (len(myDict[key]) == 0) {
       //Do something
     }
 }

Store your values with the variable names as the key, then just test the length of the value for each key.

TabsNotSpaces
  • 1,224
  • 10
  • 22
-1

You can access dynamically.

var personDetails = {name:"stanze", location: "earth" };
var p1="name";
var p2="location";
console.log(personDetails[p1]); //will print stanze
console.log(personDetails[p2]); //will print earth
stanze
  • 2,456
  • 10
  • 13
-1

Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly upon obj.

// Array-like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
print(Object.getOwnPropertyNames(obj).sort()); // prints '0,1,2'

var arr = ['a', 'b', 'c'];
print(Object.getOwnPropertyNames(arr).sort()); // prints '0,1,2,length'

// Printing property names and values using Array.forEach
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  print(val + ' -> ' + obj[val]);
});

Userful Article

Vikrant
  • 4,920
  • 17
  • 48
  • 72