Reputation: 740
Here's an example of a getter that iterates over an array and is expected to return an element for which a
is true
. But test.active
returns undefined
.
var test = {
arr: [
{id: 1, a: false},
{id: 2, a: false},
{id: 3, a: true},
{id: 4, a: false},
{id: 5, a: false},
],
get active() {
this.arr.forEach(item => {
if(item.a) return item
})
}
}
Why?
Upvotes: 0
Views: 2547
Reputation: 7488
Alternatively, you can use Array.prototype.find() function to test for a given condition and return the found element.
var test = {
arr: [
{id: 1, a: false},
{id: 2, a: false},
{id: 3, a: true},
{id: 4, a: false},
{id: 5, a: false},
],
get active() {
return this.arr.find(item => {
return (item.a === true);
});
}
}
alert(test.active.id)
https://jsfiddle.net/arqxcbkv/1/
Upvotes: 0
Reputation: 26345
Your return
statement is in an inner function, causing that function to return. Your outer function does in fact return nothing.
If you want the outer function to return, use a normal for
loop instead.
var test = {
arr: [
{id: 1, a: false},
{id: 2, a: false},
{id: 3, a: true},
{id: 4, a: false},
{id: 5, a: false},
],
get active() {
for (var i = 0, e = this.arr.length; i < e; i++) {
var item = this.arr[i];
if (item.a) return item;
}
}
}
console.log(test.active);
It might help if you understood how forEach
works.
Internally, it looks much like the following, though this is very simplified.
function forEach (array, block) {
var i, length = array.length;
for (i = 0; i < length; i++) {
// This is where your return would end up, unused, in a different context.
block(array[i], i);
}
}
forEach(['a', 'b', 'c', 'd'], item => {
return 'is meaningless here';
});
Upvotes: 2