使用JavaScript获取数组中的第一项和最后一项

2021年4月1日14:32:00 发表评论 813 次浏览

Javascript数组是一个变量, 一次包含多个值。使用索引访问第一个和最后一个元素, 使用索引0访问第一个值, 并且可以通过length属性访问最后一个元素, 该属性的值比最高数组索引多一个。

程序访问数组中的第一项和最后一项:

范例1:

<script>
// array 
let s=[3, 2, 3, 4, 5]; 
function Gfg() {
   // storing the first item in a variable 
   let f=s[0]; 
   // storing the last item 
   let l=s[s.length-1]; 
  // printing output to screen
  document.write( "First element is " + f); 
  document.write( "<br> Last element is " + l); 
} 
Gfg(); // calling the function
</script>

输出如下:

First element is 3 
Last element is 5

范例2:

<script>
// simple array
let s= [ "Geeks" , "for" , "geeks" , "computer" , "science" ]; 
function Gfg() { 
// first item of the array
  let f=s[0]; 
// last item of the array
  let l=s[s.length-1]; 
// printing the output to screen
  document.write( "First element is " + f); 
  document.write( "<br> Last element is " + l); 
  } 
Gfg(); // calling the function 
</script>

输出如下:

First element is Geeks
Last element is science

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: