克隆/复制基因敲除JS中的observablearray的最佳方法是什么?

克隆/复制基因敲除JS中的observablearray的最佳方法是什么?

问题描述:

问题确实说明了一切.我想将一个可观察的数组复制到KnockoutJS中的另一个数组.

Question says it all really. I want to copy an observable array to another in KnockoutJS.

要克隆observableArray,您需要执行以下操作:

To clone an observableArray you would want to do:

var viewModel = {
    array1: ko.observableArray(["one", "two"]),
    array2: ko.observableArray()
};

viewModel.clone = function() {
   viewModel.array1(viewModel.array2.slice(0));
};

如果您只想进行复制,则可以这样做:

If you want to just do a copy, then you would do:

viewModel.array1(viewModel.array2());

第二个示例的问题在于基础数组是相同的,因此将其压入array1或array2将导致它们都具有新值(因为它们都指向同一数组).

The problem with the second example is that the underlying array is the same, so pushing to array1 or array2 would result in both having the new value (as they both point to the same array).