【问题标题】:Why adapter function changing my num array?为什么适配器函数会改变我的 num 数组?
【发布时间】:2020-04-19 15:47:42
【问题描述】:

我想推送函数,使它不会改变我的num 数组,但它正在改变它,为什么?该函数中的nums参数是对num数组的引用

var num = []

function push(nums) {
  var orig = nums.map(x => x)
  var newNum = pushed()
  nums = orig
  return newNum
}

function pushed() {
  num.push(1)
  return num
}

console.log("new", push(num))
console.log("old", num)

【问题讨论】:

  • “为什么?” -> num.push(1)
  • 因为num.push(1)。 pre-push 创建的副本没有保存,所以当 push 函数结束时它会作为垃圾消失。也许num = orig(去掉“s”)。

标签: javascript arrays node.js


【解决方案1】:

您正在使nums 引用orig,但它不会使num 引用它。

将其更改为 num = orig 将使其工作。

var num = []

function push(nums) {
  var orig = nums.map(x => x)
  var newNum = pushed()
  num = orig
  return newNum
}

function pushed() {
  num.push(1)
  return num
}

console.log("new", push(num))
console.log("old", num)

【讨论】:

  • 我希望 num 数组保持原样(空)但推送函数正在改变它,所以我制作了一个包装适配器函数,但是变量动态分配如何在 js 中工作的概念,所以我现在记住它,更改 nums 引用只会更改它的引用,但不会更改 num 数组。
猜你喜欢
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多