【问题标题】:Showing occurences in JS array, returns correct in console but undefined on HTML?在 JS 数组中显示出现,在控制台中返回正确但在 HTML 上未定义?
【发布时间】:2021-06-21 18:12:15
【问题描述】:

正如标题所示,我在 HTML 页面上显示随机数组中每个整数的出现次数时遇到了一些问题。我希望让它显示“X 出现 N 次”或类似的东西,但是当我添加一个字符串时,它在控制台中显示为未定义,如果我只是单独放置这些值,则显示正确的值。我会证明我的意思:

function Display(id, content) { // this works fine just included for context
  let element = document.getElementById(id);
  element.innerHTML = content;
}

function GetOccurences(amt) { // here is where I have my issue

  count = {};
  arr.forEach(function(amt) {
    count[amt] = count[amt] + 1 || 1
    return count, amt;
  });

  console.log(count); // Displays correct date in console, though no room to insert dialogue 
  Display("occursId", count); //Displays undefined on HTML page

}

GetOccurences("test")

我做错了什么?在此先感谢您提供的所有帮助

【问题讨论】:

  • 你为什么有return count, amt;forEach() 不对回调函数的返回值做任何事情。另外,你不能在 JS 中返回多个值。
  • 将对象传递给Display() 只会显示[Object object]。你应该传递一个字符串。
  • GetOccurrences() 没有使用它的参数,因为您在forEach() 回调函数中重用了变量amt
  • 如果您计算整数的出现次数,GetOccurrencestest 参数有什么意义?
  • 我没有做测试.. 我想有人编辑并添加了那个,尽管我不知道为什么。

标签: javascript html arrays function


【解决方案1】:

getOccurrences() 应该将arr 作为参数,而不是amt

在调用Display()之前,您需要将返回的值转换为包含您的格式化结果的字符串。

function Display(id, content) {
  let element = document.getElementById(id);
  element.innerHTML = content;
}

function GetOccurences(arr) {

  const count = {};
  arr.forEach(function(num) {
    count[num] = count[num] + 1 || 1
  });

  const formatted = Object.entries(count).map(([num, amt]) => 
    `${num} appears ${amt} times`).join('<br>');
  Display("occursId", formatted);
}

GetOccurences([1, 2, 4, 2, 3, 8, 1, 2, 5])
&lt;div id="occursId"&gt;&lt;/div&gt;

【讨论】:

  • 谢谢! .. 我需要复习重新格式化对象中的字符串,这周只是学习对象,所以这是一个过程,但实践会取得进步
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多