为什么我的输出中有未定义的?

时间:2017-06-30 19:20:22

标签: javascript undefined console.log

请考虑以下代码:

function displayParkReport() {
  let title, part1, part2, part3;

  title = '---PARKS REPORT---\n';
  part1 = `Our ${data.all.parks.length} parks have an average of ${calcAverageParkAge()} years.`;

  data.all.parks.forEach(function(cur) {
    part2 += `${cur.name} has a tree density of ${cur.calcParkDensity()} trees per square km. \n`;
  });

  data.all.parks.forEach(function(cur) {
    if(cur.numberOfTrees > 1000) {
      part3 += `${cur.name} has more than 1000 trees. \n`;
    }
  });

  console.log(title + part1 + part2 + part3);
}

function displayStreetReport() {
  let title, part1, part2;

  title = '---STREETS REPORT---\n';
  part1 = `Our ${data.all.streets.length} streets have a total length of ${calcTotalStreetLength()} km, with an average of ${calcAverageStreetLength()} km. \n`;

  data.all.streets.forEach(function(cur) {
    part2 += `${cur.name}, built in ${cur.builtYear}, is a ${cur.size} street.\n`;
  });

  console.log(title + part1 + part2);
}

这是输出:

---PARKS REPORT---
Our 5 parks have an average of 43.600 years.undefinedNorth Park has a 
tree density of 62.500 trees per square km. 
Central Park has a tree density of 102.174 trees per square km. 
West Park has a tree density of 70.833 trees per square km. 
East Park has a tree density of 100.000 trees per square km. 
Hasan Efendi has a tree density of 235.714 trees per square km. 
undefinedCentral Park has more than 1000 trees. 
East Park has more than 1000 trees. 
Hasan Efendi has more than 1000 trees. 

---STREETS REPORT---
Our 4 streets have a total length of 122 km, with an average of 30.5 km. 
undefinedBroadway, built in 2012, is a huge street.
Cavanough, built in 1992, is a normal street.
CrazyJoe, built in 2001, is a tiny street.
WestPark, built in 1956, is a small street.

为什么输出中有随机undefined

1 个答案:

答案 0 :(得分:3)

这是因为您使用a += b,这与a = a + b相同。由于part2part3在您第一次访问时未定义,因此您尝试执行part2 = undefined + '...',这会导致undefined进入let part2 = ''; let part3 = ''; 。为它们分配初始值:

{{1}}

这样,当你第一次访问它们时,它们并没有被定义 - 它们将是空字符串。

相关问题