2016-07-16 23 views
1

我試圖訪問數組是屬性的對象,但我只能訪問屬性名稱的字母。失敗的訪問數組,這是屬性的一個對象在Javascript中

var obj = {}; 

obj.line0=[0,0]; 
obj.line1=[0,50]; 

var pointsLenght = 8; 

//things above are just test case sandbox representing small amount of real data 

var createPoints = function(obj){ 
    var i; 
    for(var x in obj){ 
     if (obj.hasOwnProperty(x)) { 
      for (i=0;i<pointsLenght;i++){ 
       if (i%2==0){ 
        x[i]=i*50; 
       } 
       else { 
        x[i]=x[1]; 
       } 
       console.log(i+" element of array "+x+" is equal "+x[i]); 
      } 
     } 
    } 
    return obj; 
} 

這是我在控制檯(火狐47.0)獲得:

0 element of array line0 is equal l 
1 element of array line0 is equal i 
2 element of array line0 is equal n 
3 element of array line0 is equal e 
4 element of array line0 is equal 0 
5 element of array line0 is equal undefined 
6 element of array line0 is equal undefined 
7 element of array line0 is equal undefined 

如何訪問數組?

+0

爲了澄清期望什麼樣的結果? – charlietfl

回答

1

操作需要做的obj [X]。 請檢查與代碼:

var obj = {}; 
 

 
obj.line0 = [0, 0]; 
 
obj.line1 = [0, 50]; 
 

 
var pointsLenght = 8; 
 

 
//things above are just test case sandbox representing small amount of real data 
 

 
var createPoints = function(obj) { 
 
    var i, elem; 
 
    for (var x in obj) { 
 
    if (obj.hasOwnProperty(x)) { 
 
     elem = obj[x]; 
 
     for (i = 0; i < pointsLenght; i++) { 
 
     elem[i] = (i % 2 == 0) ? (i * 50) : elem[1]; 
 
     console.log(i + " element of array " + elem + " is equal " + elem[i]); 
 
     } 
 
    } 
 
    } 
 
    return obj; 
 
} 
 
createPoints(obj);

2

您正在訪問屬性名稱,即字符串。 (「line0」「一號線」

訪問數組屬於該屬性的名稱,只寫你這樣的代碼,

var createPoints = function(obj){ 
    var i; 
    for(var x in obj){ 
     if (obj.hasOwnProperty(x)) { 
      for (i=0;i<pointsLenght;i++){ 
       if (i%2==0){ 
        obj[x][i]=i*50; 
        //obj[x] will give you the array belongs to the property x 
       } 
       else { 
        obj[x][i]= obj[x][1]; 
        //obj[x] will give you the array belongs to the property x 
       } 
       console.log(i+" element of array "+x+" is equal "+ obj[x][i]); 
      } 
     } 
    } 
    return obj; 
} 
+0

您的解決方案完美無瑕,我只是選擇Ayan的答案作爲一點更優雅。 – jazzgot

相關問題