获取undefined而不是string

时间:2018-06-10 19:45:17

标签: javascript arrays node.js

此程序的输出未定义,而不是字符串名称。      我将日期作为程序的输入并将日期与总统数组的现有日期进行比较。如果日期匹配,那么我想返回该特定日期的总统名称

process.stdin.resume();
process.stdin.setEncoding('utf8');

var stdin = '';
process.stdin.on('data', function (chunk) {
  //printing the value returned by presidentOnDate function
  console.log(JSON.stringify(presidentOnDate(chunk)));
});


//This is presidents array
 var presidents = [

      {"number":32,"president":"Franklin D. Roosevelt","took_office":"1933-03-04","left_office":"1945-04-12"},

      {"number":33,"president":"Harry S. Truman","took_office":"1945-04-12","left_office":"1953-01-20"},

      {"number":34,"president":"Dwight D. Eisenhower","took_office":"1953-01-20","left_office":"1961-01-20"},

      {"number":35,"president":"John F. Kennedy","took_office":"1961-01-20","left_office":"1963-11-22"},

      {"number":36,"president":"Lyndon B. Johnson","took_office":"1963-11-22","left_office":"1969-01-20"},

      {"number":37,"president":"Richard Nixon","took_office":"1969-01-20","left_office":"1974-08-09"},

      {"number":38,"president":"Gerald Ford","took_office":"1974-08-09","left_office":"1977-01-20"},

      {"number":39,"president":"Jimmy Carter","took_office":"1977-01-20","left_office":"1981-01-20"},

      {"number":40,"president":"Ronald Reagan","took_office":"1981-01-20","left_office":"1989-01-20"},

      {"number":41,"president":"George H. W. Bush","took_office":"1989-01-20","left_office":"1993-01-20"},

      {"number":42,"president":"Bill Clinton","took_office":"1993-01-20","left_office":"2001-01-20"},

      {"number":43,"president":"George W. Bush","took_office":"2001-01-20","left_office":"2009-01-20"},

      {"number":44,"president":"Barack Obama","took_office":"2009-01-20","left_office":"2017-01-20"}

    ];

// PresidentOnDate函数,它应根据输入日期返回总统名称

function presidentOnDate(date) {
    var output="";
       for(var i=0;i<presidents.length;i++){
           //console.log(presidents[i].took_office);
           if((presidents[i].took_office)==date){
              output+=presidents[i].president;
           }
      }
   return output;
}

2 个答案:

答案 0 :(得分:0)

我认为问题是你传入缓冲区而不是字符串。

尝试将chunk缓冲区更改为字符串,然后再将其传递给presidentOnDate

而不是presidentOnDate(chunk)尝试presidentOnDate(chunk.toString())

答案 1 :(得分:0)

尝试此功能可以正常使用。

当你接受输入时你面临的问题\ r \ n也是如此,所以当你比较两者时你会得到假的y输出显示为空。

EX:输入字符串:&#34; 2009-01-20 \ r \ n&#34;比较:took_office:&#34; 2009-01-20&#34; =&GT;结果错误

EX:带修剪的输入字符串:&#34; 2009-01-20&#34;比较:took_office:&#34; 2009-01-20&#34; =&GT;结果是真的

仅更改:(总统[i] .took_office)== date.trim()

function presidentOnDate(date) {

var output="";
   for(var i=0;i<presidents.length;i++){
       if((presidents[i].took_office) ==date.trim()){

          output+= presidents[i].president;
       }
  }

    return output;
 }