2016-12-04 87 views
-1

在控制檯中我有一個數組,看起來像這樣:混合JavaScript的數組

Array[3] 
    0: Object 
    1: Object 
    2: Object 
    columns: Array[2] 
    length: 3 
    __proto__: Array[0] 

的最後一個項目還沒有一個指標,但名稱columns

如何重現類似的東西? 我想:

var columns = ["age", "population"]; 
var myObj = [ 
    {age: "<5",  population: 2704659}, 
    {age: "5-13", population: 4499890}, 
    {age: "14-17", population: 2159981}, 
    columns 
]; 
console.log(myObj); 

但它給我:

// Console 
Array[4] 
    0: Object 
    1: Object 
    2: Object 
    3: Array[2] 
    length: 4 
    __proto__: Array[0] 

回答

1

數組實際上只是一個對象,你可以附加屬性,像任何其他。

你應該避免添加像這樣的屬性。

var columns = ["age", "population"]; 
 
var myObj = [ 
 
    {age: "<5",  population: 2704659}, 
 
    {age: "5-13", population: 4499890}, 
 
    {age: "14-17", population: 2159981} 
 
]; 
 

 
myObj.columns = columns 
 

 
console.dir(myObj); // check the browsers actual console to see the output 
 

 
// this proves that Array inherit's from Object 
 
console.log(myObj instanceof Array) 
 
console.log(myObj instanceof Object)

我想你最好創建自己的一個Table具有與存取不同的屬性,當你需要他們的對象。

// define the Table class 
 
class Table { 
 
    constructor(columns, rows) { 
 
    this.columns = columns 
 
    this.rows = rows 
 
    } 
 
    getColumns() { 
 
    return this.columns 
 
    } 
 
    getRows(index) { 
 
    return typeof index !== 'undefined' 
 
     ? this.rows[index] 
 
     : this.rows 
 
    } 
 
    getTable() { 
 
    return [ 
 
     this.columns, 
 
     ...this.rows.map(row => Object.values(row)) 
 
    ] 
 
    } 
 
} 
 

 
var columns = ["age", "population"]; 
 
var myObj = [ 
 
    {age: "<5",  population: 2704659}, 
 
    {age: "5-13", population: 4499890}, 
 
    {age: "14-17", population: 2159981} 
 
] 
 

 
const table = new Table(columns, myObj) 
 

 
console.log(table) 
 
console.log(table.getColumns()) 
 
console.log(table.getRows()) 
 
console.log(table.getTable())
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

+0

所以'0:Object'它意味着0是屬性? – Mahi

+0

@Mahi是的,你是對的。 –

+0

@PraveenKumar,所以我們可以使用'{}'創建數組? – Mahi