否则如果Javascript有帮助

时间:2017-09-28 01:24:16

标签: javascript

我想取两个字符串并返回更长的字符串。如果两个字符串具有相同的长度,则该函数应返回字符串' TIE'。我是javascript的新手

function getLongerString(str1,str2)
{
var a = console.log("str1");
var b = console.log("str2");
if(a.length==b.length)
{
long = "TIE";
}
     else if(a.length>b.length)
     {
        long = a; 
      }
      else
      {
        long = b;
      }
    console.log(long);
}

2 个答案:

答案 0 :(得分:0)

问题在于这两行

var a = console.log("str1").value;
var b = console.log("str2").value;

也无需创建中间变量a& b

它没有任何合理性

function getLongerString(str1, str2) {

  let long = "";
  if (str1.length === str2.length) {
    long = "TIE";
  } else if (str1.length > str2.length) {
    long = str1;
  } else {
    long = str2;
  }
  console.log(long);
}

getLongerString("Hello World", "New World")

答案 1 :(得分:0)

检查出来:



var pre = onload, getLongerStr; // for use on other loads
onload = function(){
if(pre)pre(); // change var name if using technique on another page

function getLongerStr(str1, str2){
  var s1 = str1.length, s2 = str2.length;
  if(s1 === s2){
    return 'TIE';
  }
  else{
    return s1 > s2 ? str1 : str2;
  }
}
console.log(getLongerStr('what', 'cool'));
console.log(getLongerStr('lame', 'yes'));
console.log(getLongerStr('absolutely', 'pointless'));

}