我希望从for循环返回多个值,如果我的条件满足多次
for(var i=0;i<graphVariableCount;i++)
{
if(commandResponse.GenericName == graphVariables[i].variable.index)
{
return graphVariables[i].variable.index;
}
} 在上面的代码中,我只能返回一个值。如果4-5个变量的GenericName of graphVariablei.variable.index是相同的.那我怎么能返回那个值呢。
发布于 2017-12-26 06:10:22
使用filter和map
return graphVariables.filter( s => commandResponse.GenericName == s.variable.index )
.map( s => s.variable.index );解释
filter将过滤数组,只获得匹配的值。map将迭代过滤后的数组,并且只从相同的数组中获得s.variable.index。发布于 2017-12-26 06:11:10
var values = [];
for(var i=0;i<graphVariableCount;i++)
{
if(commandResponse.GenericName == graphVariables[i].variable.index)
{
values.push(graphVariables[i].variable.index);
}
}
return values;发布于 2017-12-26 06:13:38
你可以用下面的情调来形容:
var results= [];
for(var i=0;i<graphVariableCount;i++)
{
if(commandResponse.GenericName == graphVariables[i].variable.index)
{
results.push( graphVariables[i].variable.index);
}
} https://stackoverflow.com/questions/47974508
复制相似问题