[英]When taking values from an object, does unshift() change the source object?
This question sparked when I was setting the base case of the following code:当我设置以下代码的基本情况时,引发了这个问题:
function withoutReverse(str, arrayFor = []){
arrayFor.unshift(str[0]);
if (str.length === 1)
return arrayFor.join("");
else return withoutReverse(str.slice(1), arrayFor) }
let hola = "hello";
withoutReverse(hola);//-->olleh
I thought that the base should be str.length === 0
, cause I assumed that unshift literally took each element from the source object to put it into arrayFor
.我认为基数应该是str.length === 0
,因为我假设 unshift 从字面上将源 object 中的每个元素放入arrayFor
。 Then, I realized that that was what I was using slice
for.然后,我意识到这就是我使用slice
的目的。
I didn't found a conclusive information in mdn.我在 mdn 中没有找到确凿的信息。 Am I right?我对吗? unshift()
doesn't really take those values (when stored in an object)? unshift()
并没有真正采用这些值(当存储在对象中时)? if so, how is that handled in memory?如果是这样,在 memory 中是如何处理的?
Thank you谢谢
When you get to the 5th call:当您接到第 5 个电话时:
console.log(str) // "o"
arrayFor.unshift(str[0]); // str[0] === "o"
console.log(str.length) // "1" because accessing the property here does not change it.
Therefore your exit condition is now true.因此,您的退出条件现在为真。
For functions in JS:对于 JS 中的函数:
Extra info about strings:关于字符串的额外信息:
Unlike some programming languages (such as C), JavaScript strings are immutable.与某些编程语言(例如 C)不同,JavaScript 字符串是不可变的。 This means that once a string is created, it is not possible to modify it.这意味着一旦创建了字符串,就无法修改它。
return 'cat'[1] // returns "a" return 'cat'[1] // 返回 "a"
When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed.当使用括号表示法进行字符访问时,尝试删除这些属性或为这些属性赋值将不会成功。 The properties involved are neither writable nor configurable.所涉及的属性既不可写也不可配置。 (See Object.defineProperty() for more information.) (有关详细信息,请参阅 Object.defineProperty()。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.