在 JavaScript 中获取返回值并退出 forEach?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35449664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grab the return value and get out of forEach in JavaScript?
提问by Maryam
How can I modify this code so that I can grab the field.DependencyFieldEvaluated value and get out of the function as soon I get this value?
如何修改此代码,以便我可以获取 field.DependencyFieldEvaluated 值并在获得此值后立即退出函数?
function discoverDependentFields(fields) {
fields.forEach(function (field) {
if (field.DependencyField) {
var foundFields = fields.filter(function (fieldToFind) { return fieldToFind.Name === field.DependencyField; });
if (foundFields.length === 1) {
return field.DependencyFieldEvaluated = foundFields[0];
}
}
});
}
采纳答案by lxe
Use a good old vanilla for loop:
使用一个很好的旧香草 for 循环:
function discoverDependentFields(fields) {
for (var fieldIndex = 0; fieldIndex < fields.length; fieldIndex ++) {
var field = fields[fieldIndex];
if (field.DependencyField) {
var foundFields = fields.filter(function(fieldToFind) {
return fieldToFind.Name === field.DependencyField;
});
if (foundFields.length === 1) {
return foundFields[0];
}
}
}
}
Well, if you want to stay fancy, use filter
again:
好吧,如果您想保持花哨,请filter
再次使用:
function discoverDependentFields(fields) {
return fields.filter(function(field) {
if (field.DependencyField) {
var foundFields = fields.filter(function(fieldToFind) {
return fieldToFind.Name === field.DependencyField;
});
if (foundFields.length === 1) {
return foundFields[0];
}
}
})[0];
}
回答by behzad besharati
instead of fields.forEach you can use fields.map. here is an example:
您可以使用 fields.map 代替 fields.forEach。这是一个例子:
var source=[1,2,3,4,5];
var destination=source.map(function(item){
if(item==3)
return 'OUTPUT';
}).filter(function(item){return item;})[0];
console.log(destination); // prints 'OUTPUT'
回答by Ravi Tiwari
Use return
statement where you want to break-out like below.
return
在您想要突破的地方使用语句,如下所示。
[1, 2, 3, 4, 5, 6].forEach(function(value){
if(value > 2) return;
console.log(value)
});