【问题标题】:Declare a javascript object between brackets to choose only the element corresponding to its index在括号之间声明一个javascript对象以仅选择与其索引对应的元素
【发布时间】:2026-01-22 15:40:01
【问题描述】:

我在一本书中找到了这个样本,这是我第一次看到这个符号。 显然它比做一个开关要短一千倍。但它是什么? 当我执行typeof(status) 时,它返回未定义。

我想了解它是什么,以便在我的下一个代码中更频繁地应用它!

function statusformId(id) {
  const status = ({
    0: 'in the bed',
    1: 'face to your computer',
    2: 'a little bit silly',
    3: 'nowhere'
  })[id];
  return status || 'Unknow status: ' + id;
}
console.log('statusformId(2) ...', statusformId(2)); // a little bit silly
console.log('statusformId() ...', statusformId());   // Unknow status: undefined

谢谢!

【问题讨论】:

  • 这不是一个有效的语法!贴出完整代码...
  • @ManasKhandelwal 它可能在类或对象字面量中,所以还有一个额外的}。方法有效。
  • 你传递给statusformId的值是什么?如果不是 0 到 3 之间的数字,typeof(status) 将是未定义的
  • 这是一个对象文字,其中一个键可以立即访问。见这里:jsfiddle.net/qbc1y60o(首先使用 switch 运行数字并不是一个理想的方法)
  • () 是 js 中类似于运算符的子表达式,它允许您执行 (1+2).toString() 之类的操作,并且由于表达式内部是一个对象,因此该对象被解析,因此能够被 @987654329 索引@。如果 id 有效,typeof status 应该返回 String

标签: javascript ecmascript-6 iteration value-iteration


【解决方案1】:
const a = {0:'zero'}
console.log(a[0]);

相同
const a = ({0:'zero'})[0]
console.log(a);

您最终是在尝试通过索引访问对象属性。你的代码可以写成如下。

function statusformId(id){
      const status = {
          0: 'in the bed',
          1: 'face to your computer',
          2: 'a little bit silly',
          3: 'nowhere'
        }

      return status[id] || 'Unknow status: '+id
}

PS - 你的代码 sn-p 是错误的。您错误地在代码块中添加了一个额外的“}”

【讨论】:

    【解决方案2】:

    首先修复一些问题

    • 在函数之前添加“函数”。

    这是一个工作示例:

        function statusformId(id){
          const status = (
            {
              0: 'in the bed',
              1: 'face to your computer',
              2: 'a little bit silly',
              3: 'nowhere'
            }
          )[id];
          return status || 'Unknow status: '+id
        }
        console.log(statusformId(0));
        console.log(statusformId(1));
        console.log(statusformId(2));
        console.log(statusformId(3));
        console.log(statusformId(4));
    

    将返回

    in the bed
    face to your computer
    a little bit silly
    nowhere
    Unknow status: 4
    

    原因:

    这表示一个具有一些索引的对象,其中 0 的值为 'in the bed', ... 。

    {
      0: 'in the bed',
      1: 'face to your computer',
      2: 'a little bit silly',
      3: 'nowhere'
    }
    

    将对象包装在子表达式中并添加索引将创建对象并返回传递的索引的值。

          const status = (
            {
              0: 'in the bed',
              1: 'face to your computer',
              2: 'a little bit silly',
              3: 'nowhere'
            }
          )[id];
    

    当使用对象不知道的 id 时,返回 undefined。 使用 || 将返回 'Unknow status: '+id 当 status 具有虚假值(如 undefined, null, false, ... ),否则返回实际值。

      return status || 'Unknow status: '+id
    

    【讨论】:

      最近更新 更多