查找字符串中最长的单词 - JavaScript [英] Find longest word in string - JavaScript

查看:30
本文介绍了查找字符串中最长的单词 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 python 执行一项任务,我需要这方面的帮助,我将

I am currently on a task in python and i need help with this and i am to

编写一个名为longest的函数,它将接受一串空格分隔的单词并返回最长的单词.

Write a function called longest which will take a string of space separated words and will return the longest one.

例如:

longest("This is Andela") => "Andela"
longest("A") => "A"

这是样本测试

const assert = require("chai").assert;

describe("Module 10 - Algorithyms", () => {
describe("longest('This Is Andela')", () => {
    let result = longest("This Is Andela");
    it("Should return 'Andela'", () => {
        assert.equal(result, 'Andela');
    });
});

describe("longest('This')", () => {
    let result = longest("This");
    it("Should return 'This'", () => {
        assert.equal(result, 'This');
    });
});

describe("longest(23)", () => {
    let result = longest(23);
    it("Should return ''", () => {
        assert.equal(result, '');
    });
});
});

这是我试过的

function longest(str) {
str = "This is Andela";
var words = str.split(' ');
var longest = '';

for (var i = 0; i < words.length; i++) {
  if (words[i].length > longest.length) {
    longest = words[i];
  }
}
return longest;
}

但我的代码似乎只通过了第一个测试用例.考虑到我是 javascript 新手,我需要更改什么才能通过其他两个第一个用例

But my code seem to only pass the first test case.Please what do i need to change to pass the other two first case considering i am new to javascript

推荐答案

你需要在你的函数中删除这一行:

You need to remove this line in your function:

str = "This is Andela";

您的函数应该是(添加检查 str 是否为字符串):

You function should be (added check if str is string):

function longest(str) {
    if(typeof str !== 'string') return '';
    var words = str.split(' ');
    var longest = '';

    for (var i = 0; i < words.length; i++) {
      if (words[i].length > longest.length) {
        longest = words[i];
      }
    }
    return longest;
}

这篇关于查找字符串中最长的单词 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆