【问题标题】:Create variable outside function to use inside function with parameter在函数外部创建变量以使用带参数的内部函数
【发布时间】:2019-12-10 00:47:55
【问题描述】:

我正在尝试创建一个全局变量以在其他函数中使用。我正在创建条件语句,以便我可以在多个函数中使用这些变量,而无需编写冗余代码。

let x = "";
if (filters.group == "day") {
  x = new Date(elem.date);
} else if (filters.grou == "month") {
  x = new Date(elem.year, elem.month)
}

使用的函数:

$.getJSON(jsonOne, result => {
  result.forEach(elem => {
    series1.data.push({
      x: +xaxis,
      y: elem.starts
    });

    series2.data.push({
      x: +xaxis
      y: elem.completes
    });
  });
});

$.getJSON(jsonTwo, result => {
  result.forEach(elem => {
    series3.data.push({
      x: +xaxis,
      y: elem.rev
    });

    series4.data.push({
      x: +xaxis,
      y: elem.val
    });
  });
}),

错误:

Uncaught ReferenceError: elem is not defined

x = new Date(elem.date); 出错

我明白为什么我会收到错误,但我不知道如何解决它。请帮忙!

【问题讨论】:

  • 第一个代码示例与第二个有什么关系?看来elem 不在范围内
  • x = new Date(elem.date); 在代码中相对于 $.getJSON 调用的位置在哪里?最简单的解决方案可能是将创建日期的东西转换为可以从 getJSON 中调用的函数。请记住,您还需要访问过滤器。
  • 我知道它不在范围内,但考虑到我在这么多函数中使用它,有没有办法在范围外使用变量?
  • @Shilly 我该怎么做?
  • 你可以,因此我们询问它在代码中的位置,因此我们知道哪些变量必须在哪里可用。但这只是不太理想的结构。

标签: javascript jquery json function scope


【解决方案1】:

我在想这样的事情:

你创建了一个函数,当你给它元素和过滤器作为参数时,它会返回一个日期对象。

这里的问题是,如您所见,您还需要filters。还有series1。还有xaxis。因此,不推荐使用像这样的全局变量的解决方案。但是解释更好的 JS 结构是一个完全不同的问题和答案,你可以通过搜索在这里的某个地方找到。

/* getJSON mockup for testing */
const getJSON = function( url, callback ) {
  callback([
    {
      date: '2019-01-01T00:00:00.000Z',
      year: 2019,
      month: 0,
      starts: 24
    },
    {
      date: '2019-03-13T14:51:02.021Z',
      year: 2019,
      month: 2,
      starts: 29
    }
  ]);
};

const cast_date = function( elem, filters ) {
  if ( filters.group === 'day' ) return new Date(elem.date);
  else if ( filters.group === 'month' ) return new Date(elem.year, elem.month);
  else throw new Error( `cannot create date for element ${ elem }, no valid filter group: ${ filters.group }` );

};

const filters = {
  group: 'day'
};

const series1 = {
  data: []
};

const xaxis = '20';

getJSON( 'jsonOne', result => {
  result.forEach(elem => {
  
    const date = cast_date( elem, filters );
    
    console.log( `created date: ${ date }` );
  
    series1.data.push({
      x: +xaxis,
      y: elem.starts
    });

  });
  console.log( series1 );
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2021-08-20
    • 2010-09-12
    相关资源
    最近更新 更多