我如何在JavaScript中的函数外访问变量

时间:2019-06-13 17:10:07

标签: javascript

我想在函数外部访问const newdata

    function updateFields(response) {
        $("#FIELDSET").removeProp('disabled');

        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(response, "text/xml");
        const data = xmlDoc.getElementsByTagName("responses")[0].innerHTML;
        const rdata = data.split('//')[0]
        const payload = data.split(':1:1,')
            .map(x => x.split('='))
            .reduce((obj, x) => {
                obj[x[0].replace(/\./g, '_')] = x[1];
                return obj;
            }, {})

        const newdat="string";


        CO_CODE=payload.CO_CODE.split(':1:1')[0]
        const {AMOUNT, INT_RATE, TERM, FREQUENCY, REP_START_DATE, CUSTOMER_ID, INSTALMENT} = payload;

    }

3 个答案:

答案 0 :(得分:3)

您可以将值分配给在函数外部声明的变量,但是由于const newdat的作用域在函数内部,因此您将无法在函数外部访问它。

类似这样的东西:

let newdat;
function updateFields(response) {
    $("#FIELDSET").removeProp('disabled');

    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(response, "text/xml");
    const data = xmlDoc.getElementsByTagName("responses")[0].innerHTML;
    const rdata = data.split('//')[0]
    const payload = data.split(':1:1,')
        .map(x => x.split('='))
        .reduce((obj, x) => {
            obj[x[0].replace(/\./g, '_')] = x[1];
            return obj;
        }, {})

    newdat="string";


    CO_CODE=payload.CO_CODE.split(':1:1')[0]
    const {AMOUNT, INT_RATE, TERM, FREQUENCY, REP_START_DATE, CUSTOMER_ID, INSTALMENT} = payload;

}

请注意,在这种情况下,由于变量声明未定义,您可能需要在使用它之前对其进行测试,或者在声明它时将其定义为默认值,例如空字符串。

答案 1 :(得分:2)

let newdat;
function updateFields(response) {
  $("#FIELDSET").removeProp('disabled');

  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(response, "text/xml");
  const data = xmlDoc.getElementsByTagName("responses")[0].innerHTML;
  const rdata = data.split('//')[0]
  const payload = data.split(':1:1,')
      .map(x => x.split('='))
      .reduce((obj, x) => {
          obj[x[0].replace(/\./g, '_')] = x[1];
          return obj;
      }, {})

  newdat="string";


  CO_CODE=payload.CO_CODE.split(':1:1')[0]
  const {AMOUNT, INT_RATE, TERM, FREQUENCY, REP_START_DATE, CUSTOMER_ID, INSTALMENT} = payload;

}
/* run the function */
console.log(newdat); // string

答案 2 :(得分:0)

如果newdat不特定于或不特定于您的updateFields方法,则可以将其维护在updateFields范围之外;每当调用updateFields时更新它。

let newdat = '';
function updateFields() {
    // ...
    newdat = "string";
    // ...
}

function someOtherFunction() {
    console.log( 'newdat =' + newdat ); // would log the current value of `newdat` when called
}

let newdat = '';

function updateFields() {
  newdat = "string";
}

function someOtherFunction() {
  console.log('newdat = ' + newdat); // would log the current value of `newdat` when called
}

updateFields();
someOtherFunction();