Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can a variable be declared from passed loop parameter?

Instead of doing this manually:

let test1 = echarts.init(document.getElementById('test1'));
let test2 = echarts.init(document.getElementById('test2'));
let test3 = echarts.init(document.getElementById('test3'));
window.onresize = () => {
  test1.resize({
    height: 400,
    width: document.documentElement.clientWidth - 60,
  });
  test2.resize({
    height: 400,
    width: document.documentElement.clientWidth - 60,
  });
  test3.resize({
    height: 400,
    width: document.documentElement.clientWidth - 60,
  });
};

I’d like to iterate through the array but value get an error, can’t redeclare variable

const report = [
    'test1',
    'test2',
    'test3',
];

report.forEach((value) => {
    value = echarts.init(document.getElementById(value));
    window.onresize = () => {
        value.resize({
        height: 400,
        width: document.documentElement.clientWidth - 60,
        });
    };
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Consider restructuring using Array.prototype.map() to build an array of reports from an array of ids. Then create a single resize listener which iterates through those reports to perform a resize.

const reportIds = [
  'test1',
  'test2',
  'test3',
];

// create an array of reports from an array of ids
const reports = reportIds.map(id => echarts.init(document.getElementById(id)));

// add a single resize listener which handles all reports
window.addEventListener("resize", e => {
  for (let report of reports) {
    report.resize({
      height: 400,
      width: document.documentElement.clientWidth - 60,
    });
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading