【问题标题】:print the longest word and ignore the numbers打印最长的单词并忽略数字
【发布时间】:2021-04-05 23:01:23
【问题描述】:

我正在尝试打印字符串中最长的单词并忽略该数字, 所以即使数字最长,它也会打印最长的单词。

let userInput = "print the longest word 3372838236253 without number"; 

function longestWord(userInput) {
    let x = userInput.split(" ");
    let longest = 0;
    let word = null;
    x.forEach(function(x) {
        if (longest < x.length) {
            longest = x.length;
            word = x;
        }
    });
    return word;
}

console.log(longestWord(userInput));

【问题讨论】:

标签: javascript nan longest-substring


【解决方案1】:

isNumeric检查单词是否为数字

let userInput = "print the longest word 3372838236253 without number"; 

function isNumeric(num){
  return !isNaN(num) && !isNaN(parseFloat(num))
}

function longestWord(userInput) {
    let words = userInput.split(" ");
    let longest = 0;
    let word = null;
    words.forEach(function(w) {
        if (longest < w.length && !isNumeric(w)) {
            longest = w.length;
            word = w;
        }
    });
    return word;
}

console.log(longestWord(userInput));

【讨论】:

  • @orela123 用好的和坏的例子扩展你的问题
猜你喜欢
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多