草庐IT

javascript - 带有 in 开关的 ES6 block 作用域

coder 2024-07-20 原文

在 ES6 中,我可以实现每个案例的 block 作用域:

switch(somVar){
    case 'first': 
    {
        let itemId='foo'; 
    }
    break; 
    case 'second': 
    { 
        let itemId='bar'; 
    } 
} 

显然,itemId 也可以在顶部声明。
对于我的用例,局部范围的变量更有意义,因为在我的整体代码中,更容易识别正在发生的事情,并且有许多 case,而一些 block 包含有问题的变量而其他人则没有。

我还没有看到用于 switch/case 的 block 作用域作为常见用法。
我的问题很简单,是否有理由不这样做,无论是风格上还是其他方面。

编辑、更新示例代码以避免混淆:

const someFunc(action) => { 
    switch(action.type){ 
        case 'first': 
        { 
            let itemId=action.someObj.someProp.id; 
            //Do something with itemId
        } 
        break; 
        case 'second': 
        { 
            let itemId=action.someObj.someProp.id; 
            //Do something with itemId
        } 
        break; 
        case 'third': 
            //No use of itemId 
    } 
} 

itemId 可以在顶部声明,但我更愿意查看每个案例的属性。似乎没有立即理由在不同情况下共享变量。为本质上相同的东西“发明”不同的名称似乎也是无稽之谈。

这可能有不同的写法,但这个例子是 Flux 架构中的常见模式。

最佳答案

将逻辑抽象为函数。 switch 语句本身很难阅读,更不用说一堆逻辑和变量作用域了。将逻辑抽象为函数要好得多。此外,在抽象为函数之后,您可能会注意到并没有太多需要一起使用 switch 语句。参见 Avoid use of switch statements DockYard 风格指南的一部分。

function handleFirstCase() {
  var itemId = 'foo';
  // Do stuff with itemId
  return expectedValue;
}

function handleSecondCase() {
  var itemId = 'bar';
  // Do stuff with itemId
  return expectedValue;
}

let result;
switch(somVar){
case 'first':
  result = handleFirstCase();
  break;
case 'second':
  result = handleSecondCase();
  break;
}

注意 switch 语句是如何变成一行的。这可以很容易地提炼为字典查找:

const CASES = {
  first() {
    var itemId = 'foo';
    // Do stuff with itemId
    return expectedValue;
  },

  second() {
    var itemId = 'bar';
    // Do stuff with itemId
    return expectedValue;
  }
};

let result = CASES[someVar]();

关于javascript - 带有 in 开关的 ES6 block 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38828898/

有关javascript - 带有 in 开关的 ES6 block 作用域的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  3. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  4. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  7. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  8. ruby - 在匿名 block 中产生 - 2

    我没有理解以下行为(另请参阅inthisSOthread):defdef_testputs'def_test.in'yieldifblock_given?puts'def_test.out'enddef_testdoputs'def_testok'endblock_test=procdo|&block|puts'block_test.in'block.callifblockputs'block_test.out'endblock_test.calldoputs'block_test'endproc_test=procdoputs'proc_test.in'yieldifblock_gi

  9. ruby - Sinatra set cache_control to static files in public folder编译错误 - 2

    我不知道为什么,但是当我设置这个设置时它无法编译设置:static_cache_control,[:public,:max_age=>300]这是我得到的syntaxerror,unexpectedtASSOC,expecting']'(SyntaxError)set:static_cache_control,[:public,:max_age=>300]^我只想将“过期”header设置为css、javaascript和图像文件。谢谢。 最佳答案 我猜您使用的是Ruby1.8.7。Sinatra文档中显示的语法似乎是在Ruby1.

  10. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

随机推荐