英文:
copying an integer array to a variable inside a function
问题
只返回翻译好的部分:
我有一个整数数组
let arr=[7,1,5,3,6,4]
我正在使用这个数组以升序排序并提取原始数组中第一个最小元素的位置。我的函数定义如下:
const maxProfit = function(prices) {
let org=prices
prices.sort((a,b)=>{return a-b})
console.log(org)
let ind=org.indexOf(prices[0])
console.log(ind)
};
console.log(maxProfit([7,1,5,3,6,4]))
我对`org`的值感兴趣,它应该是[7,1,5,3,6,4],但实际上我得到的是[1,3,4,5,6,7],为什么原始数组的赋值在这里不起作用?
英文:
I have an integer array
let arr=[7,1,5,3,6,4]
i am using this array to sort it in ascending order and extract the position of the first smallest element in the original array.My function is defined as
const maxProfit = function(prices) {
let org=prices
prices.sort((a,b)=>{return a-b})
console.log(org)
let ind=org.indexOf(prices[0])
console.log(ind)
};
console.log(maxProfit([7,1,5,3,6,4]))
i was interested in the value of org which is suppose to be [7,1,5,3,6,4] instead i got it as [1,3,4,5,6,7] why the assigning of the original array not working here?
答案1
得分: 3
Arrays are not primitive types and can't be cloned with =
operator.
For a relatively small array, you can just simply clone it like this
let arr = [1,2,3]
let newArr = arr.slice()
now you can perform whatever you want on newArr
and it will not affect the original array
英文:
Arrays are not primitive types and can't be cloned with =
operator.
For a relatively small array, you can just simply clone it like this
let arr = [1,2,3]
let newArr = arr.slice()
now you can perform whatever you want on newArr
and it will not affect the original array
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论