13

我有什么,我需要什么。这简单。

默认选项(有嵌套属性):

{
  sDom: 'frt<"tfoot"lp>',
  bInfo: false,
  sPaginationType: "full_numbers",
  oLanguage: {
    sSearch: "",
    sLengthMenu: "Show _MENU_",
    oPaginate: {
      sFirst:     "|<<",
      sLast:      ">>|",
      sNext:      ">>",
      sPrevious:  "<<"
    }
  }
}

实际选项:

{
  oLanguage: {
    oPaginate: {
      sNext:      "MODIFIED"
    }
  }
}

$.extend 的结果:

{
  sDom: 'frt<"tfoot"lp>',
  bInfo: false,
  sPaginationType: "full_numbers",
  oLanguage: {
    oPaginate: {
      sNext:      "MODIFIED"
    }
  }
}

我需要的是使用实际选项正确扩展默认选项并获得以下结果(一个属性已被修改):

{
  sDom: 'frt<"tfoot"lp>',
  bInfo: false,
  sPaginationType: "full_numbers",
  oLanguage: {
    sSearch: "",
    sLengthMenu: "Show _MENU_",
    oPaginate: {
      sFirst:     "|<<",
      sLast:      ">>|",
      sNext:      "MODIFIED"
      sPrevious:  "<<"
    }
  }
}

问题是 $.extend 函数忽略了嵌套属性并且只操作第一级属性。现在我已经手动 $.extend 每个嵌套属性,但我想这不是一个解决方案。

4

1 回答 1

50

您需要通过作为第一个参数传递的递归副本:true

var defaults = {...}
var actual = {...}

//recursively merge to a blank object
console.log($.extend(true,{}, defaults, actual))​
于 2012-06-05T05:53:49.097 回答