如何在JS中的两个不同类型的数组列表中使用相同的数组?

时间:2019-02-04 06:57:59

标签: javascript typescript

我有两个下拉菜单,它们引用具有不同标签的一个数组,从,到

var list = [{
  "label": "test1",
  "value": 1
},
{
  "label": "test2",
  "value": 2
}]

var temp = [];

list.forEach(l => {
temp.push({"value": l.value, "label": l.label})
}) 

var fromlist = temp;
var tolist = temp;

fromlist.unshift({value: null, label: "select from"});

tolist.unshift({value: null, label: "select to"});

console.log(fromlist, 'From');
console.log(tolist, 'To');

我的问题是从清单到清单都是相同的。

如何解决此问题?

4 个答案:

答案 0 :(得分:1)

您的问题是,当您将fromlist设置为temp时,您将引用内存中存在的数组(例如:数组temp存在于内存位置A中,fromlist现在指向数组所在的内存位置A。因此,当您将tolist设置为等于temp时,您就将它指向与fromlist相同的数组(例如:tolist也指向了内存位置{{ 1}}中的临时数组所在的位置。这样一来,您的两个变量都可以引用内存中的同一数组。

要解决此问题,您可以将A的内容散布到其自己的数组中,从而以相同的内容有效地在内存中创建一个新数组。

请参见下面的工作示例:

temp

答案 1 :(得分:1)

在JS中,数组是通过引用传递的,因此在进行//connection code con.Open(); SqlCommand cmd = new SqlCommand("SELECT amount FROM Mst_Charges WHERE registration_charges IN('OPD_CHARGES', DR.Charges')", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { txtopd_charges.Text = ??? txtdr_charges.Text = ??? } else { } } catch (Exception ex) { } } var fromlist = temp; var list = temp时,它们都是引用同一数组。您可以使用数组扩展切片来解决此问题。因此, [... temp] temp.slice()将返回一个新数组。

fromlist

答案 2 :(得分:1)

最简单的解决方案是使用spread运算符。保存多行代码,也许更优化。

const temp = [{"label": "test1", "value": 1},{"label": "test2","value": 2}];

const from = [{value: null, label: "select from"}, ...temp];
const to = [{value: null, label: "select to"},...temp];

console.log('From', from );
console.log('To', to );

答案 3 :(得分:0)

问题是您正在创建temp变量作为引用副本。

代码:

const list = [{"label": "test1", "value": 1},{"label": "test2","value": 2}];
const fromlist = list.slice();
const tolist = list.slice();

fromlist.unshift({value: null, label: "select from"});
tolist.unshift({value: null, label: "select to"});

console.log('From:', fromlist);
console.log('To:', tolist);