【问题标题】:How to add properties to an array in JSDoc?如何在 JSDoc 中向数组添加属性?
【发布时间】:2021-04-28 11:23:52
【问题描述】:

我有一个 Series 对象数组。

它是一个规则的对象数组,通过与此类似的代码添加了一个函数:

let series = loadSeriesFromDatabase();
series.getByName = (name)=>{return series;}

我现在尝试以多种方式将此函数(getByName)添加到 SeriesList。我最接近的是将系列记录为{Object} 并像这样添加它:

/**
 * @callback GetByNameFn
 * @param {string} name Name of the series
 * @returns {Series} The series that matches given name
 */
/**
 * @typedef {Object} SeriesList
 * @property {GetByNameFn} getByName
 */
/**
 * @type {SeriesList}
 */
let series = [];

但这留下的系列不是Series[],而是Object,这不是我想要的......

上面的代码将getByName 识别为函数,但如果我将其更改为@typedef {Series[]} SeriesList,它将停止工作...

有没有办法让它也可以处理数组,还是我做错了?

【问题讨论】:

    标签: javascript jsdoc


    【解决方案1】:

    我采用了您最初的尝试并修改了 JSDocs 以获得我认为您正在寻找的结果。

    能够拥有一个包含该功能的系列列表。

    /**
     * @callback GetByNameFn
     * @param {string} name Name of the series
     * @returns {Series} The series that matches given name
     */
    /**
     * @typedef {Object} SeriesFunctions
     * @property {GetByNameFn} getByName
     */
    /**
     * @typedef {object} Series
     * @property {string} name
     * @property {int} year
     */
    /**
     * @type {Series[]&SeriesFunctions}
     */
    let series = [];
    
    // Usage
    series.getByName();
    
    // Other Usage for the autocomplete fields.
    series[0].name
    

    【讨论】:

      【解决方案2】:

      以你的方式做这件事有点奇怪。

      如果我们改变它会怎么样

      /**
       * @typedef Series yow Obj.
       * @property {number} id identifier.
       * @property {string} firstName the firstName.
       * @property {string} lastName the lastName.
       *
       * @callback GetByNameFn
       * @param {string} name Name of the series.
       * @returns {Series} The series that matches given name.
       *
       * @typedef {Array<Series>} SeriesList
       *
       * @typedef SeriesWrapper
       * @property {SeriesList} list The list of all yow `Series`.
       * @property {GetByNameFn} getByName
       *
       */
      
      /**
       * @type {SeriesWrapper}
       */
      const data = {
          list: [
                  {id:1, firstName: "troll-1", lastName: "trollmon-1"},
                  {id:2, firstName: "troll-2", lastName: "trollmon-2"},
                  {id:3, firstName: "troll-3", lastName: "trollmon-3"},
                  {id:4, firstName: "troll-4", lastName: "trollmon-4"},
              ],
          getByName: function (name) {
              // code
          }
      }
      
      

      创建一个具有列表属性的对象并向其中添加 yow 项。

      const yowObj = {
        list: [],
        func: ()=>
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-25
        • 2020-12-29
        • 1970-01-01
        • 2011-11-09
        相关资源
        最近更新 更多