【如何获取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 >
输出如下:
在单击按钮之前:
文章图片
单击按钮后:
文章图片
方法二:
- 采用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 >
输出如下:
在单击按钮之前:
文章图片
单击按钮后:
文章图片
推荐阅读
- jQuery 多类选择器用法介绍
- 微处理器(μC)和微处理器(μP)有什么区别()
- Granblue Fantasy评测(简约之美)
- 众神与怪兽,彩虹六隔离区和看门狗(军团延迟)
- python循环语句和循环控制语句用法- Python入门开发教程
- python变量类型学习笔记总结 – Python入门开发教程
- 赠品(杀手皇后Black [关闭])
- 赠品–哥斯拉(数字怪兽之王[关闭])
- 复仇者联盟,超热(心智控制删除,并扎根)