复制整数数组到函数内的变量

huangapple go评论58阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月9日 14:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定