什么是不可改变的意思? [英] What does immutable mean?

查看:255
本文介绍了什么是不可改变的意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果字符串是不可变的,那是否意味着....
(让我们假设JavaScript)

If a string is immutable, does that mean that.... (let's assume JavaScript)

var str = 'foo';

alert(str.substr(1)); // oo

alert(str); // foo

这是否意味着,当在字符串上调用方法时,它将返回修改后的字符串,但它不会改变初始字符串?

Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?

如果字符串是可变的,那是否意味着第二个 alert()还会返回 oo 吗?

If the string was mutable, does that mean the 2nd alert() would return oo as well?

推荐答案

这意味着一次实例化对象时,无法更改其属性。在你的第一个警报中,你不会改变foo。你正在创建一个新的字符串。这就是为什么在你的第二个警报中它将显示foo而不是oo。

It means that once you instantiate the object, you can't change its properties. In your first alert you aren't changing foo. You're creating a new string. This is why in your second alert it will show "foo" instead of oo.


这是否意味着,在$ b $上调用方法时ba字符串,它将返回修改后的
字符串,但它不会更改
的初始字符串?

Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?

是。创建字符串后,没有任何内容可以更改。现在,这并不意味着您无法将新的字符串对象分配给 str 变量。你只是无法改变str引用的当前对象。

Yes. Nothing can change the string once it is created. Now this doesn't mean that you can't assign a new string object to the str variable. You just can't change the current object that str references.


如果字符串是可变的,那么
是否意味着第二个alert()也会返回o $

If the string was mutable, does that mean the 2nd alert() would return oo as well?

技术上,不,因为substring方法返回一个新字符串。使对象变为可变,不会改变方法。使其变为可变意味着从技术上讲,你可以使子串改变原始字符串而不是创建一个新字符串。

Technically, no, because the substring method returns a new string. Making an object mutable, wouldn't change the method. Making it mutable means that technically, you could make it so that substring would change the original string instead of creating a new one.

这篇关于什么是不可改变的意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆