Can';t在Javascript中从映射迭代返回值
我在尝试使用Javascript从.map返回值时遇到问题。这是我的密码:Can';t在Javascript中从映射迭代返回值,javascript,ecmascript-6,Javascript,Ecmascript 6,我在尝试使用Javascript从.map返回值时遇到问题。这是我的密码: function LineaDeSuccion() { const carga = vm.cargaTotal / vm.numeroEvaporadores; vm.succion.map(i => { if (i.temperatura == vm.tempSel) { const cargas = Object.keys(i).map(function(key) {
function LineaDeSuccion() {
const carga = vm.cargaTotal / vm.numeroEvaporadores;
vm.succion.map(i => {
if (i.temperatura == vm.tempSel) {
const cargas = Object.keys(i).map(function(key) {
return i[key];
});
// I need to return this value in my function
return getKeyByValue(i, closest(cargas, carga));
}
// Obviously I can't do it because the value it's encapsulated into the map callback.
// How can I solve it?
return value;
});
}
如果要返回
映射
之外的值,则必须设置位于映射
之外的变量,然后在映射
内设置该值:
function LineaDeSuccion() {
const carga = vm.cargaTotal / vm.numeroEvaporadores;
let value = "defaultValue"; // default value
vm.succion.map(i => {
if (i.temperatura == vm.tempSel) {
const cargas = Object.keys(i).map(function(key) {
return i[key];
});
value = getKeyByValue(i, closest(cargas, carga)); // new set value
}
});
return value;
}
一种方法是使用
Array.prototype.find
在数组中找到所需的值,然后在获得该值后执行所需的转换
function LineaDeSuccion() {
const carga = vm.cargaTotal / vm.numeroEvaporadores;
const i = vm.succion.find(i => i.temperatura == vm.tempSel);
if (i === undefined) {
throw Error("can't find what I want in the array");
}
const cargas = Object.keys(i).map(function (key) {
return i[key];
});
return getKeyByValue(i, closest(cargas, carga));
}
请注意,这种方法不会迭代整个数组,而是在找到匹配项后立即中断
find
循环。如果数组中有多个元素i
满足条件i.temperaturea==vm.tempSel
,这将返回第一个匹配项,而不是最后一个。这对我有效。另一个解决方案给我带来了未定义的回报。