首页 > 解决方案 > 我如何计算数字并计算它?(我使用 isNaN())

问题描述

我的代码如下。我正在使用isNaN(),但问题是它仍然有效

function numberSearch(str) {
  let sum = 0
  let strCount = 0
  
  if (str === "") {
    return 0
  };
  
  for (let i = 0; i < str.length; i++) {
    if (isNaN(Number(str[i]))) {
      strCount = strCount + 1 // if it's true, +1
    }
    
    sum = sum + Number(str[i]) // if it's a number 
  }
  
  return Math.round(sum / strCount);
}

//debugger;

let output = numberSearch('Hello6 ');
console.log(output); // --> 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1

我如何计算数字并计算它?

当我使用调试器时,总和是NaN..我无法理解。

标签: javascript

解决方案


问题是sum = sum + Number(str[i])即使isNaN(Number(str[i])) === true因为它在if块之外,它也正在执行。您需要将它包装在else块内,以便它仅在前一个条件为假时执行。

function numberSearch(str) {
  let sum = 0
  let strCount = 0

  if (str === "") {
    return 0
  };

  for (let i = 0; i < str.length; i++) {
    if (isNaN(Number(str[i]))) {
      strCount = strCount + 1 // if it's true, +1
    } else {
      sum = sum + Number(str[i]) // if it's a number 
    }
  }

  return Math.round(sum / strCount);
}

//debugger;

let output = numberSearch('Hello6 ');
console.log(output); // --> 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1

另一种方法是使用continue声明。想一想continue你对函数早期return的思考方式,除了循环。

例如,您编写了:

function numberSearch(str) {
  // . . .

  if (str === "")
    return 0

  // . . .
}

这称为“提前返回”或“提前退出”。可以在循环中使用相同的技术:

for (let i = 0; i <= 10; i++) {
  if (i % 3 === 0) // matches every multiple of 3 (3, 6, 9, etc.)
    continue;

  console.log(i)
}

这是您的代码,这次使用continue.

function numberSearch(str) {
  let sum = 0
  let strCount = 0

  if (str === "") {
    return 0
  };

  for (let i = 0; i < str.length; i++) {
    if (isNaN(Number(str[i]))) {
      strCount = strCount + 1 // if it's true, +1
      continue
    }

    sum = sum + Number(str[i]) // if it's a number 
  }

  return Math.round(sum / strCount);
}

//debugger;

let output = numberSearch('Hello6 ');
console.log(output); // --> 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1

我建议您使用该if-else版本,因为对于像这样简单的循环,使用continue增加了一些不必要的金属开销。
话虽如此,如果循环中的逻辑增长(else语句中的部分),您可能会发现如果您使用continue方法很容易阅读。最后,真正重要的是您个人认为更容易阅读的内容。


推荐阅读