在没有if的情况下循环js以获得特定值

Loop in js for specific value without if

我使用下面的代码,效果很好,但我想知道在 JS 中是否有一种方法可以避免 if 并在循环内执行它,如果它有帮助,我也想使用 lodash

for (provider in config.providers[0]) {
    if (provider === "save") {
        ....

怎么样:

for (provider in config.providers[0].filter(function(a) {return a === "save"}) {
    ...
}

您可以使用 _.chain, filter by a value, and then use each 将调用链接在一起,为每个筛选结果调用一个函数。但是,您必须在最后添加一个最终的 .value() 调用,以便它计算您刚刚构建的表达式。

我认为对于简短、简单的条件块,if 语句更容易、更易读。如果您在一个对象或集合上组合多个操作或执行复杂的过滤、排序等,我会使用 lodash- 更具体地说是链接。

var providers = ['hello', 'world', 'save'];

_.chain(providers)
  .filter(function(provider) {
    return provider === 'save';
  }).each(function(p) {
    document.write(p); // your code here
  }).value();
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>

编辑:我的错误; filter 没有重载,您只能在其中提供文字值。如果你想进行文字值检查,你必须提供一个函数,如我上面修改后的答案。

基本上,您正在测试 config.providers[0],它是一个对象,是否包含一个名为 save 的 属性(或其他一些动态值,我正在使用一个变量调用 provider 将该值存储在我下面的示例代码中)。

您可以使用这个代替 for .. in .. 循环:

var provider = 'save';
if (config.providers[0][provider] !== undefined) {
  ...
}

或使用@initialxy 的(更好!)建议:

if (provider in config.providers[0]) {
  ...
}

我认为你那里的东西非常好,干净且可读,但既然你提到了 lodash,我会试一试。

_.each(_.filter(config.providers[0], p => p === 'save'), p => {
    // Do something with p
    ...
});

请注意,ECMAScript 6 的箭头 function/lambda 直到版本 45 才到达 Chrome。

策略,您正在寻找某种策略模式,

Currenlty the save is hardcoded but what will you do if its coming from other varible – Al Bundy

var actions = {
  save: function() {
    alert('saved with args: ' + JSON.stringify(arguments))
  },
  delete: function() {
    alert('deleted')
  },
  default: function() {
    alert('action not supported')
  }
}

var config = {
  providers: [{
    'save': function() {
      return {
        action: 'save',
        args: 'some arguments' 
      }
    },
    notSupported: function() {}
  }]
}

for (provider in config.providers[0]) {
  (actions[provider] || actions['default'])(config.providers[0][provider]())
}

按下“运行 代码片段”按钮将显示两个弹出窗口 - 请注意

楼主没有明确说明是否需要输出 应该是 single save - 或包含 all 出现的数组 保存.

这个答案显示了后一种情况的解决方案。

const providers = ['save', 'hello', 'world', 'save'];
const saves = [];
_.forEach(_.filter(providers, elem => { return elem==='save' }),
  provider => { saves.push(provider); });
console.log(saves);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.js"></script>