【问题标题】:i created two functions, both are working but when i when i put them together they are not我创建了两个功能,两者都在工作,但是当我把它们放在一起时,它们就不行了
【发布时间】:2022-01-16 07:16:04
【问题描述】:

下面的函数检查一个数字是否为奇数并记录它们

function OddNumFinder(x) {
    if (x%2==1) {
    y = console.log(x+' is a odd number');
    x = x%2
    return console.log(x);
    }
}
im_num = []

这个函数创建一个随机数数组

function collConjecture(x) {
    while (x !== 1) {
        if (x%2 == 1) {
            x = (x*3)+1
        } else {
            x = x/2
        }
        im_num.push(x)
    }
}

这行得通

collConjecture(26)
list = im_num
console.log(list);

我不知道我在这里做错了什么

var yetha = OddNumFinder(collConjecture(26))
console.log(yetha);

【问题讨论】:

  • console.log 不返回任何内容 (undefined),因此 yetha 的值为 undefined
  • collConjecture 什么也不返回。您正在将 void 传递给 OddNumFinder 函数。
  • 只需添加您面临的错误。
  • 你到底想在这里做什么?

标签: javascript arrays function


【解决方案1】:

进行以下更改

//Takes a number and checks for odd
function OddNumFinder(x) {
  if (x%2 == 1) {
    console.log(x + ' is a odd number');
    x = x%2
  }
}


function collConjecture(x) {
  im_num = []
  while (x !== 1) {
      if (x%2 == 1) {
          x = (x*3)+1
      } else {
          x = x/2
      }
      im_num.push(x)
  }
  return im_num
}

//call map on each number to check for odd
collConjecture(26).map(item => {
  OddNumFinder(item)
})

输出:-

13 is a odd number
5 is a odd number
1 is a odd number

【讨论】:

  • 它有效,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2018-08-11
  • 2016-05-24
  • 2015-11-04
  • 1970-01-01
  • 2021-08-31
相关资源
最近更新 更多