I have following code:
$.each(data, function (key, val) {
var items = val.items;
console.log(val.id);
if (val.id === this.id) {
console.log('hello');
}
});
In the above code, I am looping through data
which is a JSON object. Then I compare the id
of val
with this.id
which has value of 4
. Thus what I want is when val.id (4)
equals to this.id (4)
then log hello
, however, since data
has several objects so it logs several hellos.
Why and how can I make it so that it says hello only when it matches that condition and get out of that loop?
In the function defined within the call to each()
, this === val.
If you're trying to compare to the value of this.id
from before the call to each, you'll need to cache it, like so:
var someId = this.id;
$.each(data, function (key, val) {
var items = val.items;
console.log(val.id);
if (val.id === someId) {
console.log('hello');
}
});
As Alison has said, this
in side the function is val
so you need some kind of caching. (This feature is useful when you only need the value but not the key, so you can have function(){...}
and use this
instead)
Also, if you want to break from the .each
loop, return false inside the loop function:
var someId = this.id;
$.each(data, function (key, val) {
var items = val.items;
console.log(val.id);
if( val.id === someId ) {
console.log('hello');
return false;
}
});
as specified in the documentation .
what you have here is, you are comparing the same data in if condition which is always true.. this
represent to current element in each loop which in your case is data
and same goes to val
too.. you can try with console.log(this)
inside the loop ..
if( val.id === this.id ){ //this will always be true
so you have to rethink your logic ..... what actually you need to match in the(that) condition.
when it matches that condition and get out of that loop
try it out in fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.