Reputation: 987
I would like to loop through the whole array, and stop when my if-condition
is met, then put the value in my var checked
.
If the if-condition
is not met, the var should be set false
.
When I put the break
my script outputs false
, which it shouldn't since 2002
exists in the array.
subscriber = [2001, 2002, 2004]
for(i = 0; i < subscriber.length; i++) {
if (subscriber[i].ID == '2002') {
checked = 'true';
break; //added break here
} else {
checked = 'false';
}
Write(checked);
}
(please don't mind the properties of the object e.g. ID)
Upvotes: 0
Views: 2884
Reputation: 10998
It looks like your subscriber
array isn't formed correctly. Your for
loop seems to indicate that each element in subscriber
is an object with an id
property.
Working off this assumption, you can optimize your code as follows:
const subscribers = [{ id: 2001 }, { id: 2002 }, { id: 2004 }];
const checked = subscribers.some(subscriber => subscriber.id === 2002);
The some function will return true
if anything in the array passes the check.
Upvotes: 3