【问题标题】:What does the square bracket after the number mean in javascript? [duplicate]javascript中数字后面的方括号是什么意思? [复制]
【发布时间】:2020-06-13 15:50:07
【问题描述】:

2[a],其值为undefined

下面的代码会报错Cannot access 'b' before initialization

let a = 1, b = 2
[a, b] = [b, a];

我知道这是由于b = 2 后面缺少分号造成的。添加分号后

let a = 1, b = 2;
[a, b] = [b, a];

它工作正常。是数字后面的方括号造成的吗?如果是这样,它在javascript中的含义是什么?

【问题讨论】:

  • @Pointy 这是一个属性访问,这就是为什么它不是语法而是运行时错误。

标签: javascript


【解决方案1】:

是不是数字后面的方括号造成的?

是的。

如果是这样,它在javascript中的含义是什么?

这是一个属性访问操作,就像:

const array = [1, 2, 3];

const b = array[1];
//             ^^^−−−−−−−−−−−−−−−−−−−−−−−−−

console.log(b); // 2

您可以对原语进行属性访问操作,事实上您经常这样做。例如,在字符串原语上:

console.log("hi".toUpperCase()); // "HI"

// or

const fiftyFifty = Math.random() < 0.5;
const method = fiftyFifty ? "toUpperCase" : "toLowerCase";

console.log("Hi"[method]()); // "hi" or "HI"

或者使用数字原语:

console.log(2["toString"]()); // "2"

const n = 2;
console.log(n.toString());    // "2"

console.log(2..toString());   // "2"

当您这样做时,将使用相关原型(String.prototypeNumber.prototype 等)并在某些情况下以松散模式创建临时对象(例如,new String("hi")new Number(2))。

【讨论】:

  • 为什么不演示2["toString"]()
  • @Bergi - 我最初是这样做的,但人们不会“经常”这样做。 :-) 他们经常使用let n = 2; n.toString(),但不是2["toString"]()(或2..toString()),所以我认为更熟悉的东西可能会更好......
  • 我会两者兼而有之。 :-)
猜你喜欢
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 2014-10-24
  • 2018-10-14
  • 1970-01-01
  • 2013-05-28
  • 2014-07-28
  • 1970-01-01
相关资源
最近更新 更多