对象和数组解构的复杂性,当传递给生成器时

时间:2019-07-18 01:33:10

标签: javascript arrays object generator destructuring

试图对学习生成器和进行销毁进行一些最后的修饰,我举了一个例子,并记入了脑海,我将通过生成器的初始值“ i”进行迭代。从一个对象开始,除非我做了几次意外发现,否则它不会起作用。

一旦它与用于设置参数的对象一起工作,我决定也将箭头函数添加到混合中,但是会有一些有趣的行为。

如代码所示,该对象同时使用初始值“ i”和箭头函数,但是以这种方式通过genVal()顶部的if语句,仍然需要查看其结构再次声明。我怀疑这与范围界定有关,但是通常会给定两个引用相同分配的let语句的错误,即传递的参数“ setup”(可能包含数组或对象)。

我已经剥离了初始值'i'和另一个版本中的arrow函数,但是那里也有一些奇怪的事情。

你能告诉我这是怎么回事吗?而且,如果知道的话,从设置而不是从生成器发送乘数“ valFactor”的更好的方法是什么,因为稍后我可能想将其转换为模块而不重新访问代码,除非进行一些重构需要吗?

function handler(val) {
  retVal = {}
  str = val.toString()
  // str = val
  dotIdx = str.indexOf(".")
  braceIdx = str.indexOf("(")
  retVal['head'] = str.slice(0, dotIdx)
  retVal['tail'] = str.slice(dotIdx + 1, braceIdx)
  return retVal
}

function calc(setup) {
  for (val of genVal(setup)) {
    // stringify and strip val using a handler
    let {
      head,
      tail
    } = handler(val)
    console.log(`Head: ${head} Tail: ${tail}`)
  }
}

function* genVal(setup) {
  // all passed will be objects so first distract for the object that is an array
  if (Array.isArray(setup)) {
    console.log("\n___________________________________________")
    console.log('array path')
    // changed from let to var re. stackoverflow comment
    // it's considered a bad solution as it breaks scope, and isn't the
    // accepted destructuring way, which would have a declaration
    // before the if...else block and retain these assignments, 
    // without var, let or const, and, for the object path, the statement wrapped in parentheses
    // see the answer below  
    var [i, iters, valTop, valBottom, valFactor] = setup
  } else { // is going to be an object, for sure
    console.log("\n___________________________________________")
    console.log('object path')
    // changed from let to var re. stackoverflow comment
    var {
      i,
      iters,
      valTop,
      valBottom,
      valFactor
    } = setup
  }


  // // // arrSetup 'mode' 
  // w/ obj destructure below commented out
  // we traverse the array path, above
  // an error results without this duplication
  // and the arrow fn passed as valFactor does not 'work'
  //////////

  // let [i, iters, valTop, valBottom, valFactor] = setup

  // // // objSetup 'mode' 
  // w/ arr destructure above commented out
  // we traverse the object path, above
  // an error results without this duplication
  //////////

  // let {
  //  i,
  //  iters,
  //  valTop,
  //  valBottom,
  //  valFactor
  // } = setup

  for (i; i <= iters; i++) {
    console.log(i)
    // console.log(valBottom)
    // console.log(valFactor)
    // newTail = valBottom + valFactor
    // console.log(newTail)

    if (i !== 1) {
      console.log(valTop + i)
      yield(valTop + i) / valFactor(valBottom)(i)
    } else {
      console.log(valTop)
      yield valTop / valBottom
    }
  }
}

// Two 'setup' types, one using arrSetup and the other using objSetup
// i, iters, valTop, valBottom, valFactor
// arrSetup = [1, 2, 22, 7, (m) => m+.0101]
arrSetup = [1, 2, 22, 7, m => n => m+n]


objSetup = {
  "i": 1,
  "iters": 2,
  "valTop": 22,
  "valBottom": 7,
  "valFactor": m => n => m+n,
  // "valFactor": (i) => i + .9999,
}

calc(objSetup)
calc(arrSetup)

更新:

因此,范围问题很容易得到解决。谢谢。

因此,范围界定问题比我想象的要有趣得多,并且给出的解决方案确实比我提出问题之前更加了解了Javascript语法。这里的代码非常接近原始代码。看一下Barmar如何保持genVal()函数的词法作用域,但可以使用if ... else块中的结构分解来实例化变量。陌生的东西,但恕我直言很少。

在第一篇文章中,代码的箭头功能不起作用,因为数组中的元素数量与赋值和解构不一致。 h!此后已解决。事实证明,传递函数然后尝试使用它没有任何作用,尽管我仅尝试了一些语法技巧以使valFactor对生成器的yield语句中的valBottom起作用。在离线状态下,我已经放弃了传递一个函数,并且只是暂时(现在)在生成器中硬编码了valFactor。

现在我正在研究一种技术,该技术允许将函数(完整或箭头)作为数组或对象之一或两者的值传递给生成器,并使其在yield表达式中使用现有的解构语法(实际上是Barmar提供的语法)。

已解决:

函数currying解决了我的问题。

代替此: i => i * .9090 如果在上下文中传递m和n的值,则此方法有效。     curried = m => n => m*n 并致电:     curried(varforM)(varforN)

注意:在调用中省略其中一个变量将导致箭头功能之一作为返回值。

1 个答案:

答案 0 :(得分:1)

您不能使用解构let来初始化对象或数组中的变量。由于let语句位于ifelse块中,因此作用域将只是那些块,而不是封闭函数。

您可以做的是先声明变量,然后在ifelse中使用解构赋值。

请注意,对对象的破坏性分配必须用括号括起来,因为如果语句以{开头,则假定它是块的开始,而不是对象的开始。

function handler(val) {
  retVal = {};
  str = val.toString();
  // str = val
  dotIdx = str.indexOf(".");
  braceIdx = str.indexOf("(");
  retVal['head'] = str.slice(0, dotIdx);
  retVal['tail'] = str.slice(dotIdx + 1, braceIdx);
  return retVal;
}

function calc(setup) {
  for (val of genVal(setup)) {
    // stringify and strip val using a handler
    let {
      head,
      tail
    } = handler(val);
    console.log(`Head: ${head} Tail: ${tail}`);
  }
}

function* genVal(setup) {
  let i, iters, valTop, valBottom, valFactor;
  // all passed will be objects so first distract for the object that is an array
  if (Array.isArray(setup)) {
    console.log("\n___________________________________________");
    console.log('array path');
    [i, iters, valTop, valBottom, valFactor] = setup;
  } else { // is going to be an object, for sure
    console.log("\n___________________________________________");
    console.log('object path');
    ({i, iters, valTop, valBottom, valFactor} = setup);
  }

  for (i; i <= iters; i++) {
    console.log(i);
    console.log(valBottom);
    console.log(valFactor);
    newTail = valBottom + valFactor;
    console.log(newTail);

    if (i !== 1) {
      console.log(valTop + i);
      yield(valTop + i) / valBottom + valFactor;
    } else {
      console.log(valTop);
      yield valTop / valBottom;
    }
  }
}

// Two 'setup' types, one using arrSetup and the other using objSetup
// i, iters, valTop, valBottom, valFactor
arrSetup = [1, 2, 3, (i) => i * .0101];

objSetup = {
  "i": 1,
  "iters": 2,
  "valTop": 22,
  "valBottom": 7,
  "valFactor": (i) => i * .0101,
};

calc(objSetup);
calc(arrSetup);