如何创建数组的副本?

时间:2013-04-27 22:20:24

标签: javascript

我有这段代码:

const settings = {
            notes: [new musicnote(480,400,"wav/1.wav","cyan",true)],
            emiters: [new emiter(300,240), new emiter(340,240)]
        }

var notes = [];
var emiters = [];

var LoadLevel = function (level) {
    if(settings[level] !== undefined){
        currentLevel = level;
        notes = settings[level].notes;
        emiters = settings[level].emiters;
    }
}

当我在游戏中更改emiters数组(删除或添加一些)时,它会对settings.emiter数组执行相同操作。所以我的问题是 - 如何在settings对象中传递一个新数组而不是对数组的引用?

1 个答案:

答案 0 :(得分:4)

您可以使用Array.slice

执行此操作
var original = [];
var copy = original.slice();

// to test:
copy.push("foo");
alert(original.length); // 0