Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';t使用模板字符串中的forEach函数进行输出_Javascript_Dom_Destructuring - Fatal编程技术网

Javascript Can';t使用模板字符串中的forEach函数进行输出

Javascript Can';t使用模板字符串中的forEach函数进行输出,javascript,dom,destructuring,Javascript,Dom,Destructuring,输出: const categoriesLght = document.querySelectorAll('#categories .item').length; console.log(`There are ${categoriesLght} clasifications.`); const h2s = document.querySelectorAll('h2'); const heading = h2s.forEach(element => console.log(`Clasif

输出:

const categoriesLght = document.querySelectorAll('#categories .item').length;
console.log(`There are ${categoriesLght} clasifications.`);
const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
  console.log(`Clasification: ${element.textContent}`),
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
  console.log(`Quantity: ${el.childElementCount}`),
);
如果我尝试将函数放入模板字符串中,将出现错误。试图找到一种方法让它发生。期望输出为:

There are 3 clasifications.
Clasification: Student
Clasification: Fish
Clasification: Rocket
Quantity: 3
Quantity: 5
Quantity: 6
我正在寻找一种方法,如何将ForEach方法的结果放入模板字符串中,以实现类似的效果(我想我正在寻找一些解构):


循环一个并使用索引引用另一个

str = [h2s.forEach, quantity.forEach]([category, count])=> (console.log(`Clasification: ${category.textContent},
Quantity: ${count.childElementCount} `));

您可以先尝试将值保存到变量:

const h2s = document.querySelectorAll('h2');
const quantity = document.querySelectorAll('h2 + ul');

h2s.forEach((element, i) =>
  console.log(`Classification: ${element.textContent}, Quantity: ${quantity[i].childElementCount}`),
);

那么更好的解决方案是3个循环而不是1个?
const h2s = document.querySelectorAll('h2');
const quantity = document.querySelectorAll('h2 + ul');

h2s.forEach((element, i) =>
  console.log(`Classification: ${element.textContent}, Quantity: ${quantity[i].childElementCount}`),
);
const clarifications = [];
const quantities = [];

const h2s = document.querySelectorAll('h2');
const heading = h2s.forEach(element =>
    clarifications.push(element.textContent);
);

const quantity = document.querySelectorAll('h2 + ul');
quantity.forEach(el =>
    quantities.push(el.childElementCount);
);

clarifications.forEach((clarification, i) => {
    console.log('Clarification:', clarification);
    console.log('Quantity:', quantities[i]);
});