current position:Home>How does JavaScript copy arrays instead of references

How does JavaScript copy arrays instead of references

2022-05-15 02:05:36thankseveryday

Method 1

const arr1 = ['a', 'b', 'c']
const arr2 = arr1.concat()
console.log(arr2)  // ['a', 'b', 'c']

arr2.push('d')
console.log(arr1)  // ['a', 'b', 'c']
console.log(arr2)  // ['a', 'b', 'c', 'd']

Method 2

const arr1 = ['a', 'b', 'c']
//  Writing a 
const  arr2 = [...arr1]
//  Write two 
const [...arr2] = arr1
console.log(arr2)  // ['a', 'b', 'c']

arr2.push('d')
console.log(arr1)  // ['a', 'b', 'c']
console.log(arr2)  // ['a', 'b', 'c', 'd']

copyright notice
author[thankseveryday],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120527259434.html

Random recommended