简体   繁体   中英

Global variable doesn't work-largestString() which takes an array of strings as input and returns the largest string in this array

 <p id="longeststring">
</p>
  <script>

  var arr=[];
  var longest=arr[0];

  function largestString(arr)
  {
   for (var i=0;i<arr.length;i++)
       {if(arr[i].length>=longest.length)
          {longest=arr[i]}


       }
   return longest;

  }
  z=["what","am","I","doing","now"]
  document.getElementById("longeststring").innerHTML=largestString(z)
</script>

So when var longest=arr[0] is inside the function it works, but when I take it outside, it shows"longest not defined". Why is that? I thought by putting it outside the function, the variable "longest" could update itself.

Thank you in advance.

When you put the expression var longest=arr[0]; outside the function, the arr refers to the global variable. Its value is set to [] , so value of its first item is undefined.

But if you put the expression var longest=arr[0]; inside the scope, the arr refers to the parameter, so it will have the correct value.

@bran0's answer is correct. I suggest you can write var longest = "" instead of var longest = arr[0] because arr 's length may be zero and longest will be undefined in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM