0

flag is always false. how can I do?

code here:

var list = ['NOVALUE','VALUE','NOVALUE'];
var flag = false;
angular.forEach(list, function(value){
    if('VALUE' === value){
        flag = true;
    }
});
console.log(flag);

sorry, i missed something

4
  • what are you trying to do..? Commented May 28, 2015 at 10:51
  • 2
    because last element making it false again 'VALUE' === 'NOVALUE' Commented May 28, 2015 at 10:51
  • 1
    if you're trying to check if an array has a value, you can use indexOf Commented May 28, 2015 at 10:52
  • 1
    You'd need to break out of that loop when you found a match. Unfortunately there's no breaking mechanism in angular.forEach: stackoverflow.com/questions/13843972/angular-js-break-foreach Commented May 28, 2015 at 10:54

4 Answers 4

1

You should either use .indexOf(), as Alexander demonstrates:

var list = ['NOVALUE','VALUE','NOVALUE'];

var flag = list.indexOf('VALUE') !== -1;

console.log(flag);    

or .some() in the more general case:

var list = ['NOVALUE','VALUE','NOVALUE'];

var flag = list.some(function (value) {
    return value === 'VALUE';
});

console.log(flag);
Sign up to request clarification or add additional context in comments.

Comments

0
var list = ['NOVALUE','VALUE','NOVALUE'];
var flag = false;
angular.forEach(list, function(value){
    if (value === 'VALUE'){
        flag = true;
    }
    else{
        flag = false;
    }
    console.log(flag);
});

//false, true, false

1 Comment

Answers are better if you provide an explanation of why\how they work
0

Use break; so that whentrue statement comes it will go out of the loop

var list = ['NOVALUE','VALUE','NOVALUE'];
        var flag = false;
        for(var i=0;i<list.length;i++){
        if('VALUE' === value)
         {
          flag=true;                
          break;
          }else
          flag=false;
        }
        console.log(flag);

Comments

0

Because the last value in list is "NOVALUE" so it is always false. You can do

flag = list.indexOf('VALUE') > -1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.