【问题标题】:how to return two object values in java script [duplicate]如何在javascript中返回两个对象值[重复]
【发布时间】:2015-02-26 14:29:08
【问题描述】:

我知道java脚本是动态语言,我想知道是否有选项 返回类似于

的内容
 Inte.prototype.getM = function(sMethod) {
     return  this._mMet[sMet].ret && 
     return this._mMeth[sMet].ret.default;
  };

目前,当我按原样尝试时出现错误(这并不奇怪 :))。

【问题讨论】:

  • 创建另一个包含这两个值的对象并返回它!
  • 返回一个对象(或数组)
  • 将它们推入数组并返回

标签: javascript jquery


【解决方案1】:

你可以返回一个数组:

 return  [this._mMet[sMet].ret,this._mMeth[sMet].ret.default];

或通过一个对象:

return  {'one': this._mMet[sMet].ret, 'two': this._mMeth[sMet].ret.default};

编辑

根据 OP 评论,他希望对这些值进行一些验证:

if (typeof this._mMet[sMet].ret == 'undefined' || typeof this._mMeth[sMet].ret.default == 'undefined') { 
    return false; 
} else { 
    return  {'one': this._mMet[sMet].ret, 'two': this._mMeth[sMet].ret.default};
}

【讨论】:

  • 只是最后一个问题假设我使用第二个我应该如何验证 this._mMet[sMet].ret && this._mMet[sMet].ret.defult 有值,因为当他们 undefiend 我得到错误
  • 退货前。只需做一个 if 语句。 if (typeof this._mMet[sMet].ret == 'undefined' || typeof this._mMeth[sMet].ret.default == 'undefined') } //do something for eg return false, } else { //add them to the object and return}
  • 能否更新为答案
  • 我已经编辑了我的答案。
【解决方案2】:

你只能退回一件东西。但也可以是数组:

Inte.prototype.getM = function(sMethod) {
     return  [this._mMet[sMet].ret, this._mMeth[sMet].ret.default];
  };

【讨论】:

    【解决方案3】:

    你可以返回一个对象

    Inte.prototype.getM = function(sMethod) {
         return {
             ret: this._mMet[sMet].ret,
             retDefault: this._mMeth[sMet].ret.default
        };
    };
    

    然后你可以使用它访问它

    var returnObject = inte.getM(arguements);
    var ret = returnObject.ret //equvalent to returnObject['ret'];
    var retDefault= returnObject.retDefault //equivalent to returnObject['retDefault'];
    

    【讨论】:

      【解决方案4】:

      您可能需要使用对象数组吗? 例如:

      var array = [];
      array.push(this._mMet[sMet].ret);
      array.push(this._mMet[sMet].ret.default);
      return array;
      

      【讨论】:

        【解决方案5】:

        最好的办法是

        function a(){
             var first=firstObject;
             var second=secondObject;
             return {first:first,second:second};
        }
        

        然后使用

        a().first // first value
        a().second // second value
        

        【讨论】:

          【解决方案6】:

          尝试返回数组:

          Inte.prototype.getM = function(sMethod) {
               return new Array(this._mMet[sMet].ret,this._mMeth[sMet].ret.default);
          };
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-03-27
            • 2020-04-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-23
            • 1970-01-01
            • 2016-04-25
            相关资源
            最近更新 更多