循环的JavaScript更改原始列表变量 [英] javascript for loop changes original list variable

查看:41
本文介绍了循环的JavaScript更改原始列表变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为响应的对象集合,我正在创建另一个名为 object 的变量,它是一个空对象,并创建 object.array 并将其设置为响应变量。

I have a collection of objects called the response and I am creating another variable called object that's an empty object and creating object.array and set it to the response variable.

我想我正在创建一个新的作用域。但是,如果将 object.array 中的年龄设置为null,这会将我的响应数组中的年龄设置为 null

I would think I am creating a new scope. However, if I set the age inside object.array as null, this sets the age in my response array to null.

为什么会发生这种情况,如何创建不影响原始变量的重复变量?我需要保持上述变量不变。因此对象需要是一个对象,我需要创建一个在其中设置为响应的数组,并且它必须位于 for循环内。

Why is this happening and how can I create a duplicate variable that doesn't affect the original? I need to keep the above variables as is. So object needs to be an object and I need to create an array within which is set to the response and it needs to be inside a for loop.

这是我的代码:

function runThisLoop () {

    var response = [{
        name: 'Name A',
        age: 2
    },
    {
        name: 'Name B',
        age: 7
    }]


    var object = {}
    object.array = response

    for (var val of object.array) {
        val.age = null
    }

    console.log("response", response)
    console.log("object.array", object.array)
}

runThisLoop()


推荐答案

您只是通过引用复制它们,这意味着它们在内存中的同一位置,因此,无论您尝试修改其中一个,还是修改另一个,以防止您应该通过以下两种方式中的一种通过您:

You are just copying them by reference which means they are in the same location in memory so whatever you try to modify one of them the other will get modified in order to prevent this you should pass you in either of these ways:


  1. 使用 Array.from()

  1. Using Array.from()



object.array = Array.from(response);




  1. 使用 slice()

  1. Using slice()



object.array = response.slice();




  1. 使用传播语法( ...

  1. Using spread syntax (...)



object.array = [...response];




  1. 使用 JSON.parse / JSON.strigify

  1. Using JSON.parse/JSON.strigify



object.array = JSON.parse(JSON.stringify(response));

但是在您的特定情况下,只有最后一个选项才能按预期工作嵌套数组,您需要元素的深层副本

But in your particular case, only the last option will work as expected since you got a nested array, you need a deep copy of your element.

因此,最终结果应该是这样的:

So the final result should be something like this:

function runThisLoop() {

  var response = [{
      name: 'Name A',
      age: 2
    },
    {
      name: 'Name B',
      age: 7
    }
  ]


  var object = {}
  object.array = JSON.parse(JSON.stringify(response));

  for (var val of object.array) {
    val.age = null
  }

  console.log("response", response)
  console.log("object.array", object.array)
}

runThisLoop()

这篇关于循环的JavaScript更改原始列表变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆