【问题标题】:Eloquent JavaScript : immutable string valuesEloquent JavaScript:不可变的字符串值
【发布时间】:2016-09-17 11:48:57
【问题描述】:

Eloquent JavaScript 说字符串值是不可变的,作为 Stackoverflow 的第一个问题的答案:Understanding Javascript immutable variable

但是如果我们写如下:var string = "hello world"; string = "permitted";,字符串真的被修改了。

我上面提到的答案只是说明对象是可变的,而不是其他值。

既然字符串可以像我刚才告诉你的那样被修改,那是不是意味着字符串原始值在'='成功时会自动转换为对象?

所以前面的代码将严格等同于:var string = new String("hello world"); string = new String("permitted")。这可以解释为什么要修改字符串的值。

【问题讨论】:

  • 你可以覆盖变量,但是你不能改变字符串,例如string.replace(something)创建一个新字符串,它不能修改字符串,因为它是不可变.
  • 但是你没有修改字符串。您只是为该变量分配了一个新字符串。
  • @NiettheDarkAbsol:是的,我同意你的看法。真的会发生吗?
  • @adeneo :所以没有任何转换字符串->字符串实例?
  • "immutable" 意味着字符串的值不能改变,这并不意味着你不能给变量分配不同的值。字符串方法不会改变原始字符串,它们只是创建一个新字符串。

标签: javascript string variables constants immutability


【解决方案1】:

你需要区分reassignment和mutation:

let x = "abc";

x = "123"; // reassignment
console.log(x);

x[0] = "9"; // mutation
console.log(x);

突变后x 仍然包含"123",因为Strings 是不可变的。如果Strings 是可变的,它当然会包含"912"

您还必须区分以下术语:

  • 变量

使用此声明 let x = "abc",您可以声明一个变量 x 并使用值 "abc" 对其进行初始化。

  • 标识符

无论何时在您的代码中使用x(声明时除外),它只是一个标识符,并且必须通过Javascript 绑定到相应的变量声明。请注意,您可以在不同的范围内拥有多个声明,例如 let x = "abc",因此需要名称绑定:

let x = "abc";

{ // another scope
  let x = "123";

  { // and yet another scope
    console.log(x); // which is the corresponding variable of this identifier?
  }
}

如果你想防止一个变量被重新赋值,你实际上可以在 ES2015 中这样做:

const x = "abc";
x = "123"; // throws an Error

请注意,您修改了变量声明以实现此行为。

【讨论】:

  • 当你说“String”是不可变的,你说的是原始值还是对象? (因为在JS中,这两个值都存在)
  • @Lern-X 字符串Object 只是一个包裹在Object 中的String 原语:let x = new String("abc")String 原语仍然是不可变的 x[0] = "x" 产生 "abc",但包装器不是:x.prop = true; x.prop 产生 true
【解决方案2】:

也许一个演示会告诉你字符串不可变意味着什么。

var stringobject = new String("test"); // or "test"; both yield same result
console.assert(stringobject.valueOf() === "test", "before");

stringobject[0] = "T"; // replace first char
console.assert(stringobject.valueOf() === "Test", "after");

console.log("Success?"); // or is it?

【讨论】:

    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多