如何获取JavaScript对象的最后一项()

【如何获取JavaScript对象的最后一项()】给定一个JavaScript对象, 任务是获取JavaScript对象的最后一个元素。
方法1:

  • 采用Object.keys()方法获取对象的所有键。
  • 现在, 使用索引来访问JavaScript对象的最后一个元素。
例子:本示例实现了上述方法。
< !DOCTYPE HTML> < html > < head > < title > How to get the last item of JavaScript object ? < / title > < / head > < body style = "text-align:center; " > < h1 style = "color:green; " > lsbin < / h1 > < p id = "GFG_UP1" style = "font-size: 15px; font-weight: bold; " > < / p > < p id = "GFG_UP2" style = "font-size: 15px; font-weight: bold; color: green; "> < / p > < button onclick = "GFG_Fun()" > click here < / button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold; "> < / p > < script > var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var Obj = { "1_prop": "1_Val", "2_prop": "2_Val", "3_prop": "3_Val" }; up1.innerHTML = "Click on the button to get" + "the last element of the Object."; up2.innerHTML = JSON.stringify(Obj); function GFG_Fun() { down.innerHTML = "The last key = '" + Object.keys(Obj)[Object.keys(Obj).length-1] + "' < br > Valuehttps://www.lsbin.com/= '" + Obj[Object.keys(Obj)[Object.keys(Obj).length-1]] + "'"; } < / script > < / body > < / html >

输出如下:
在单击按钮之前:
如何获取JavaScript对象的最后一项()

文章图片
单击按钮后:
如何获取JavaScript对象的最后一项()

文章图片
方法二:
  • 采用for循环要访问对象的所有键, 则在循环结束时, 循环变量将具有对象的最后一个键。
  • 现在, 使用索引来访问JavaScript对象的最后一个元素的值。
例子:本示例实现了上述方法。
< !DOCTYPE HTML> < html > < head > < title > How to get the last item of JavaScript object ? < / title > < / head > < body style = "text-align:center; " > < h1 style = "color:green; " > lsbin < / h1 > < p id = "GFG_UP1" style = "font-size: 15px; font-weight: bold; " > < / p > < p id = "GFG_UP2" style = "font-size: 15px; font-weight: bold; color: green; "> < / p > < button onclick = "GFG_Fun()" > click here < / button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold; "> < / p > < script > var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var Obj = { "1_prop": "1_Val", "2_prop": "2_Val", "3_prop": "3_Val" }; up1.innerHTML = "Click on the button to get" + "the last element of the Object."; up2.innerHTML = JSON.stringify(Obj); function GFG_Fun() { var lastElement; for (lastElement in Obj); lastElement; down.innerHTML = "The last key = '" + lastElement + "' < br > Valuehttps://www.lsbin.com/= '" + Obj[lastElement] + "'"; } < / script > < / body > < / html >

输出如下:
在单击按钮之前:
如何获取JavaScript对象的最后一项()

文章图片
单击按钮后:
如何获取JavaScript对象的最后一项()

文章图片

    推荐阅读