0

Hi everyone,

I am trying yo loop through an array property that is multi-valued and so the condition is if that property has what the value specified then alert with a message saying hello.. The other idea is kinda complex that is to check using RegExp...

Here is the code..

         var array = new Array();
         array.fruit= "banana, apple";
         array.vegies ="cucumber, carrot, tomatos, potatos";
         array.drinks = "coke, pepsi";

         var pep = "pepsi";
         var getVal;
         outerloop:
         for(var obj in array){
              getVal = array[obj];
                println(obj + " : " + getVal);

                if ( obj.hasOwnProperty( "pepsi") ){        here is the problem
                     alert("hello");
                     break outerloop;
                }

         }

Cheers,

4
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by AleMonteiro
0

I think you want if( getVal.indexOf("pepsi") != -1). Note that this also returns true if the given string looks like "FOO,BARpepsiBLA,BAZ". If you want to avoid that you can either split the string or use arrays instead of strings in the first place.

PS: There's no need for loop labels here as you only have one loop.

0

looking at the code I guess the "coke, pepsi" is not a property of array.drinks object. It's a value of the array.drinks property.

If you want to get pepsi or coke, you can try sepp2k suggesstion of using a split method for strings.

2

I think you're missunderstaing somethings...
First, you are not using the array as an array, but as an simple object(var array = new Object() would be prettier).
Second, pepsi is not a property of "array.drinks", it's the value.
What I think you want:

var array = new Object();

array.fruit= ["banana", "apple"];
array.vegies = ["cucumber", "carrot", "tomatos", "potatos"];
array.drinks = ["coke", "pepsi"];

outerloop:
for(var prop in array){
    var obj = array[prop];

    for(var index in obj) {
        var val = obj[index];
        if ( val == "pepsi" ){
            alert(val + " found");
            break outerloop;
        }
    }
 }

Hope it helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.