เมธอด HTML DOM Storage key() ใช้สำหรับส่งคืนชื่อคีย์ที่ดัชนีที่กำหนดในอ็อบเจ็กต์การจัดเก็บ ดัชนีถูกส่งผ่านเป็นพารามิเตอร์ไปยังวิธี key() วัตถุหน่วยเก็บข้อมูลสามารถเป็นวัตถุเซสชันหรือวัตถุ localStorage ได้
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับ −
วิธีการจัดเก็บคีย์ () โดยใช้ localStorage -
localStorage.key(index);
เมธอด Storage key() โดยใช้ sessionStorage -
sessionStorage.key(index);
ในที่นี้ ดัชนีเป็นประเภทจำนวนเต็มแทนหมายเลขคีย์ที่คุณต้องการตั้งชื่อ
ตัวอย่าง
ให้เราดูตัวอย่างสำหรับเมธอด Storage key() -
<!DOCTYPE html>
<html>
<body>
<h1 style="text-align:center">storage key() method example</h1>
<p>Get the first object key name by clicking on the below button</p>
<button onclick="keyName()">GET NAME</button>
<p id="Sample"></p>
<script>
function keyName() {
var k = localStorage.key(1);
document.getElementById("Sample").innerHTML ="The key name of the second
localStorage object is "+k;
}
</script>
</body>
</html> ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

เมื่อคลิกปุ่ม GET NAME -
