CodeLab
Show Output
 
xxxxxxxxxx
30
 
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="utf-8">
5
<title>Add New Array Elements at the Beginning</title>
6
</head> 
7
<body>
8
    <script>
9
        var fruits = ["Apple", "Banana", "Mango"];
10
         
11
        // Prepend a single element to fruits array
12
        fruits.unshift("Orange");
13
         
14
        console.log(fruits);
15
        // Prints: ["Orange", "Apple", "Banana", "Mango"]
16
         
17
        // Prepend multiple elements to fruits array
18
        fruits.unshift("Guava", "Papaya");
19
         
20
        console.log(fruits);
21
        // Prints: ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]
22
         
23
        // Loop through fruits array and display all the values
24
        for(var i = 0; i < fruits.length; i++){
25
            document.write("<p>" + fruits[i] + "</p>");
26
        }
27
    </script>
28
    <p><strong>Note:</strong> Please check out the browser console by pressing the f12 key on the keyboard.</p>
29
</body>
30
</html>
 

在微博、微信、公众号、小程序分享此示例。 如果您觉得有帮助,请给我们一个赞。