当前位置:网站首页>JS to create an array (all elements are objects)

JS to create an array (all elements are objects)

2022-06-23 06:41:00 Lanterns can only come to the classroom to experience life

js Create array ( Array elements are objects )

object

    var obj = {
    
        // attribute 1
        attribute1:' ',
        // attribute 2
        attribute2:' '
    }

Array

What is created here is an empty array , And does not specify the type of the array element

// Method 1
var arr = [];
// Method 2
var arr = new Array();

Add elements to the array

    var test = function(){
    
        // Array 
        var arr = [];
        for(let i=0;i<5;i++){
    
            // Temporary objects 
            let obj = {
    
                // attribute 1
                x: Math.random()*10 ,
                // attribute 2
                y: Math.random()*10 
            };
            arr.push(obj);
        }
        // Print properties 
        for(let i=0;i<arr.length;i++){
    
            console.log("x: "+arr[i].x);
            console.log("y: "+arr[i].y);
        }
    }

push Methods to introduce

 Insert picture description here


Console output

 Insert picture description here

原网站

版权声明
本文为[Lanterns can only come to the classroom to experience life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230506565794.html