【问题标题】:jQuery created new arrayjQuery创建了新数组
【发布时间】:2018-05-10 00:47:10
【问题描述】:

我的 jQuery 数组有问题。

我想要两个不同的数组。

var main_array = []

function create_array(){

   main_array[0] = {id: 1, status: true, number: 10};
   main_array[1] = {id: 1, status: true, number: 16};
   main_array[2] = {id: 1, status: true, number: 20};

}

function change(array, key, number){

   array[key].number = number

}

create_array()

new_array = change(main_array, 0, 20); 

console.log(main_array)

在这种情况下,我在 $main_array 数组中添加了一个元素,我想要更改编号并创建新数组,但是当我调用更改函数时,我的 main_array 更改为。

我不想更改 main_array 编号。

那是我做错了

【问题讨论】:

  • 为什么要使用美元符号作为非 jQuery 变量的前缀?您的代码中根本没有使用 jQuery。
  • 什么是 test()?
  • 你想要一个数组的副本并更改值吗?
  • 数组以引用方式给出。您需要在更改函数中创建一个新数组并返回新数组:stackoverflow.com/questions/3775480/…
  • och 对不起...测试是变化(...)

标签: javascript arrays


【解决方案1】:

数组是对象,当您将对象传递给函数时,您传递的是对对象内存位置的引用,而不是对象的副本。所以,如果接收函数修改传入的参数,它会修改原来的对象。

因为您的数组包含 对象,它们也作为对底层对象内存位置的引用传递,因此您需要为数组中的每个对象创建副本。这是通过 Object.assign() 完成的。

另外(正如我在评论中提到的),通常认为在标识符前加上美元符号是一种约定,表示标识符持有对 JQuery 包装的集合对象的引用。由于您没有在代码中的任何地方使用 JQuery,我建议您删除它们。

var main_array = [];  // <-- This is where the main array will go
var newArray =   [];  // <-- This will be where the copied array goes

function create_array(){

   main_array[0] = {id: 1, status: true, number: 10};
   main_array[1] = {id: 1, status: true, number: 16};
   main_array[2] = {id: 1, status: true, number: 20};
   
   return main_array;
}

function change(array, key, number){
   // Loop thorugh the original array:
   main_array.forEach(function(obj){
    // Make a copy of the objects in the array and put them in the new array
    newArray.push(Object.assign({}, obj));
   });
   newArray[key].number = number
}

main_array = create_array();

change(main_array, 0, 20); 

console.log(main_array, newArray)

【讨论】:

  • @sinisake 就像我写的一样。
  • 是的,在第一个演示/输出中,两个数组都被更改了,所以我很困惑...... :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2014-03-02
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多