更改数组传递给函数

mac*_*acg 5 javascript jquery underscore.js

我将2个数组传递给函数,并希望将特定条目从一个数组移动到另一个数组.moveDatum函数本身使用underscorejs的方法拒绝和过滤.我的问题是,原始数组没有改变,好像我是将数组作为值而不是作为引用传递.特定条目被正确移动,但正如我所说,效果只是本地的.我需要改变什么才能使原始阵列发生变化?

调用函数:

this.moveDatum(sourceArr, targetArr, id)
Run Code Online (Sandbox Code Playgroud)

功能本身:

function moveDatum(srcDS, trgDS, id) {
    var ds = _(srcDS).filter(function(el) {
        return el.uid === uid;
    });
    srcDS = _(srcDS).reject(function(el) {
        return el.uid === uid;
    });
    trgDS.push(ds[0]);
    return this;
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助

Pau*_* S. 2

在使用修改Arrays的方法删除之前复制每个匹配项,例如splice

function moveDatum(srcDS, trgDS, id) { // you pass an `id`, not `uid`?
    var i;
    for (i = 0; i < srcDS.length; ++i) {
        if (srcDS[i].uid === uid) {
            trgDS.push(srcDS[i]);
            srcDS.splice(i, 1); 
            // optionally break here for just the first
            i--; // remember; decrement `i` because we need to re-check the same
                 // index now that the length has changed
        }
    }
    return this;
}
Run Code Online (Sandbox Code Playgroud)