Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t在Javascript中从映射迭代返回值_Javascript_Ecmascript 6 - Fatal编程技术网

Can';t在Javascript中从映射迭代返回值

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) {

我在尝试使用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) {
        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
,这将返回第一个匹配项,而不是最后一个。

这对我有效。另一个解决方案给我带来了未定义的回报。