【问题标题】:Function returning array item for assignment函数返回数组项进行赋值
【发布时间】:2020-08-26 07:47:38
【问题描述】:

我在 js 中实现了一个拖放界面,它有两个对象表和一个作为源或目标的对象。为了执行“移动”操作,我想到了使用这两个类方法:

    _getVar(id) {
        var ind;
        switch (id[0]) {
            case 'c':
                return this.clipboard;
            case 's':
                ind = Number(id.substr(1)) - 1;
                return this.SynthPatches[ind];
            case 'f':
                ind = Number(id.substr(1)) - 1;
                return this.FilePatches[ind];
        }
    }

    
    move(from, to) {
        var fv = this._getVar(from);
        var tv = this._getVar(to);
        if (fv == undefined) return "Source empty";
        if (tv == undefined) return "Destination undefined";
        tv = fv;
        return "Ok";
    }

这不起作用。 fv 和 tv 是对正确对象的本地引用。参考 fv 被复制到 tv 然后两者都被遗忘了。 我想要一个类似于 python 中的深拷贝的东西,但看起来唯一的解决方案是内联 _getVar() 九次,这使得代码非常难看。

【问题讨论】:

  • tv = fv; 不会像您期望的那样运行,它只会为局部变量 tv 分配 fv 的值,因此 tv 将不再指向它的原始对象,并且在该函数之外不会发生任何事情,您需要一个参考示例:mainObj.tv = fv; 或 mainObj[index].tv = fv;
  • 这里的挑战是,没有单一的“mainObj”。相反,从三个可能的 mainObjects(this.SynthPatches、this.FilePatches 或 this.clipboard)中选择一个是 _getVars 任务。

标签: javascript arrays object reference


【解决方案1】:

这里减少重复的最简单方法可能是在函数中添加一个可选的第二个参数,并允许它设置和获取,例如:

_getOrSetVar(id, value) {
    var ind;
    switch (id[0]) {
        case 'c':
            if (value !== undefined) this.clipboard = value
            return this.clipboard;
            break;
        case 's':
            ind = Number(id.substr(1)) - 1;
            if (value !== undefined) this.SynthPatches[ind] = value
            else return this.SynthPatches[ind];
            break;
        case 'f':
            ind = Number(id.substr(1)) - 1;
            if (value !== undefined) this.FilePatches[ind] = value
            else return this.FilePatches[ind];
            break;
    }
}

并像这样执行更新:

this._getOrSetVar(to, this._getOrSetVar(from))

【讨论】:

  • 不错的解决方案!这些案例现在需要 break 语句,我需要处理带有异常的“未定义”情况,但这个想法很棒。
  • 很好,我添加了休息时间。未定义的检查适用于您使用该方法获取值时。
猜你喜欢
  • 1970-01-01
  • 2012-06-16
  • 2019-01-05
  • 1970-01-01
  • 2020-09-08
  • 2020-07-30
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多