代码之家  ›  专栏  ›  技术社区  ›  Hedge

将bool值转换为其字符串表示形式的最短方法(例如“true”)。

  •  0
  • Hedge  · 技术社区  · 8 年前

    基本上,我需要将“boolean”类型值转换为字符串形式的等效值( true or false ),我想知道是否存在比执行 boolval更短(即使速度较慢)的方法?真“:”假 ?

    那么,有没有一种更短的方法来完成以下任务呢?如果有帮助,所有ES2015-2018商品均可使用:)

    const boolval=true
    const boolstr=布尔瓦尔?真':'假'
    
    
    

    编辑:I created a small benchmark of the presented solutions.https://jspef.com/bool-to-string转换

    .boolVal ? 'true' : 'false?

    那么,有没有一种更短的方法来完成以下任务呢?如果有帮助,所有ES2015-2018商品均可使用:)

    const boolVal = true
    const boolStr = boolVal ? 'true' : 'false'
    

    编辑:我为提出的解决方案创建了一个小基准。https://jsperf.com/bool-to-string-conversion

    3 回复  |  直到 8 年前
        1
  •  7
  •   31piy    8 年前

    你可以打电话 toString() 在变量上获取其等效字符串:

    var a = true.toString();
    var b = false.toString();
    
    console.log(a, b, typeof a, typeof b);
        2
  •  2
  •   Bartłomiej Gładys    8 年前

    你可以用 String() 作为一个函数

    const t = String(true)
    const f = String(false)
    
    console.log(t, f, typeof t, typeof f);

    编辑

    字符串() 比…慢 toString()

    const time = 10000000
    
      console.time('toString')
      for(let i =0 ; i< time; i++)
        true.toString()
      console.timeEnd('toString')
    
      console.time('String(bool)')
      for(let i =0 ; i< time; i++)
        String(true)
      console.timeEnd('String(bool)')

    但是…如果我们不确定布尔值是否存在呢?

    const u = undefined;
    const n = null;
    
    // String()
    console.log('String( undefined ): ', String(u), typeof String(n));
    console.log('String( null ): ', String(n), typeof String(n));
    
    // toString() :) 
    
    console.log( u.toString() );
        3
  •  1
  •   Peshraw H. Ahmed    8 年前

    我认为这应该有效:

    boolStr = boolVal.toString()
    

    编辑:我已经测试过了,它可以工作了。 https://jsbin.com/bapuvoqibo/edit?html,console,output

    你可以查看这个链接

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/toString