简体   繁体   中英

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 . Then, I realized that that was what I was using slice for.

I didn't found a conclusive information in mdn. Am I right? unshift() doesn't really take those values (when stored in an object)? if so, how is that handled in memory?

Thank you

When you get to the 5th call:

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:

  • numbers/strings/booleans are passed as values
  • arrays/objects are passed as references

Extra info about strings:

Unlike some programming languages (such as C), JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it.

Source MDN

return 'cat'[1] // returns "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.)

Source MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM