如何将数组数据复制到具有数组和字段的对象

How can I copy array data to an object that has an array and also a field?

本文关键字:数组 字段 对象 数据 复制      更新时间:2023-09-26

我有:

var test;
var abc = [1,2,3];
test.active = [];
test.active.$selected = 123;

是否可以将包含[1,2,3]的数组复制到测试中。激活阵列而不使test.active。$selected = 123消失?

当我尝试test。Active = ABC,则$selected值丢失

您可以将Array.prototype.push()apply()结合使用,将元素复制到test.active数组,同时保持任何属性不变。

注意:你没有定义test作为一个对象,所以我已经改变了。

小提琴

var test = {}; // define as object
var abc = [1,2,3];
test.active = [];
test.active.$selected = 123;
// copy abc's elements to test.active, while keeping any of test.active's properties
test.active.push.apply(test.active, abc);
console.log(test.active.$selected); // 123
console.log(test.active[0]); // 1
console.log(test.active[1]); // 2
console.log(test.active[2]); // 3

事实上,是的,这是可能的。但我不确定你是否需要。以简单的方式:

var test;
test.active = [1,2,3];
test.active.$selected = 123;

在这种情况下,你将分配给test.active一个新的数组。只要所有的JavaScript都是对象,你就可以给它添加一个新属性。但从常识性的角度来看,混合两种不同的数据类型(数组和对象)并不是一个好的做法。所以在你的情况下,我建议对数组和整数值使用单独的属性:

var test;
test.active = [1,2,3];
test.$selected = 123;

注意:如果你有一个更复杂的数组,例如对象等-最好使用任何库来深度克隆它。但这取决于你的具体问题