In the previous article "How to get the median of a numeric array in JavaScript (two methods)", I introduced how to get the median of a numeric array. Interested friends can learn about it. Let’s take a look~
The main content of this article is to teach you how to use JavaScript to obtain the keys of an associative array through two methods.
First of all, let me briefly introduce to you what is an associative array?
Associative array: Associative array is used to store key-value pairs. For example, to store a student's scores in different subjects in an array, a numerically indexed array is certainly not the best choice. Instead, we can use the student names as keys in an associative array and the values will be the marks obtained by each of them. In an associative array, key-value pairs are associated with the : symbol.
The following will introduce two methods to obtain the keys of associative arrays.
Method 1:
In this method, use a for loop to traverse the entire associative array and display the key elements of the array.
Syntax:
for (var key in dictionary) { // ... }
The complete sample code is as follows: Loop through the associative array and print keys
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title></title> <script> var arr = { "牛顿": "重力", "艾伯特": "能源", "爱迪生": "灯泡", "特斯拉": "AC" }; document.write("显示的Keys: <br>"); // 循环打印keys for (var key in arr) { if (arr.hasOwnProperty(key)) { // 打印Keys document.write(key + "<br>"); } } </script> </head> <body> </body> </html>
Print results:
显示的Keys: 牛顿 艾伯特 爱迪生 特斯拉
Method 2:
Using the Object.keys() function: Object.keys() is a built-in function in JavaScript that can be used to get all the keys of an array.
Syntax:
Object.keys(obj)
The sample code is as follows: Use Object.keys() to access the keys of the associative array.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title></title> <script> var arr = { "牛顿": "重力", "艾伯特": "能源", "爱迪生": "灯泡", "特斯拉": "AC" }; // 获取keys var keys = Object.keys(arr); document.write("Keys显示如下:<br>"); // 打印keys document.write(keys); </script> </head> <body> </body> </html>
The printing results are as follows:
Keys显示如下: 牛顿,艾伯特,爱迪生,特斯拉
Finally, I would like to recommend "JavaScript Basic Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of Two ways to get the keys of an associative array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!