【问题标题】:Given an array, return one value at a time with each function call给定一个数组,每个函数调用一次返回一个值
【发布时间】:2018-01-19 05:34:53
【问题描述】:

给定一个数组,每次调用函数时一次返回一个值。我需要创建一个函数,在其中给定一组项目,我需要一次返回一个值,直到最后一个值。

我查看了一些答案,我认为这是可行的,但这是一个无限循环。

我接近解决方案了吗?我哪里错了?

function functionName() {
  
  var vals =
  ["shot_type","shot_height","shot_angle","framed","scene_depth"];
  for(var i=0; i<vals.length; i++) {
    functionName(vals[i]);
  }
}

functionName(); //expect 'shot type'
functionName(); //expect 'shot height'

【问题讨论】:

  • 你一直打电话给functionName。
  • 你应该看看迭代器。

标签: javascript


【解决方案1】:

你可以使用迭代器,但我不知道那些我会使用闭包。

let functionName = () => {
  let i = -1;
  var vals = ["shot_type","shot_height","shot_angle","framed","scene_depth"];
  
  functionName = () => {
    i++;
    return vals[i];
  }
  
  return functionName();
}

console.log(functionName());
console.log(functionName());
console.log(functionName());

这里i定义在新定义的functionName的范围之上,这是新函数保留的对i的引用。

【讨论】:

  • 嘿,我喜欢这个解决方案,但是 sn-p 跳过了第一项?我注意到它首先返回"shot_height",什么时候应该是"shot_type"?
  • 我的错,i 需要从 -1 开始,因为我们在返回之前递增。我已经更新了我的答案。
  • 嗯,为什么不从0 开始然后return vals[i++] 而不是在上一行递增?
  • 当然可以,但我喜欢冗长。让别人更容易理解!
  • 挺好的,内部函数是箭头函数,作用域一样
【解决方案2】:
  const functionName = (iter => () => iter.next().value)(vals.values());

这会构建一个迭代器并将其封闭在一个 IIFE 中,因此您可以对其进行迭代。

【讨论】:

    【解决方案3】:

    不是 100% 确定你想如何“重新开始”,但我回到了顶部/0 之一。闭包然后调用一个函数来从中获取值。假设至少 1。

    var functionName = function() {
      var whichone = -1;
      var vals = ["shot_type", "shot_height", "shot_angle", "framed", "scene_depth"];
      this.getvalue = function() {
        whichone++;
        if (whichone === vals.length) {
          whichone = 0;
        }
        return vals[whichone];
      };
      return this;
    }();
    
    console.log(functionName.getvalue()); //expect 'shot type'
    console.log(functionName.getvalue()); //expect 'shot height'
    console.log(functionName.getvalue());// angle
    console.log(functionName.getvalue());// framed
    console.log(functionName.getvalue());//scene_depth
    console.log(functionName.getvalue());// back to shot type

    【讨论】:

      【解决方案4】:

      数组已经是迭代器,所以如果你可以使用迭代器(es6+),那么你可以这样做:

      var vals = ["shot_type","shot_height","shot_angle","framed","scene_depth"];
      const iter = vals[Symbol.iterator]();
      
      console.log(iter.next().value);
      console.log(iter.next().value);
      console.log(iter.next().value);
      // And so on.
      
      // The iter.next() method returns an object: {value: any, done: boolean};
      // When done is true, then there are no more values to get from the iterator.

      【讨论】:

        猜你喜欢
        • 2019-03-09
        • 2021-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-03
        • 1970-01-01
        • 2016-10-27
        相关资源
        最近更新 更多