[英]Why does this getter return undefined?
Here's an example of a getter that iterates over an array and is expected to return an element for which a
is true
. 这是一个getter的示例,该getter遍历数组,并期望返回a
为true
的元素。 But test.active
returns undefined
. 但是test.active
返回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? 为什么?
Your return
statement is in an inner function, causing that function to return. 您的return
语句在内部函数中,导致该函数返回。 Your outer function does in fact return nothing. 实际上,您的外部函数不会返回任何内容。
If you want the outer function to return, use a normal for
loop instead. 如果您希望外部函数返回,请使用普通的for
循环。
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. 如果您了解forEach
工作方式,可能会有所帮助。
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'; });
Alternatively, you can use Array.prototype.find() function to test for a given condition and return the found element. 另外,您可以使用Array.prototype.find()函数测试给定条件并返回找到的元素。
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/ https://jsfiddle.net/arqxcbkv/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.