2016-12-04 12 views
-1

私はこのようになります配列を持っている:混合JavaScriptのArray

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