无法访问Javascript中对象属性的数组

时间:2016-07-16 17:46:43

标签: javascript arrays object

我正在尝试访问作为对象属性的数组,但我只能访问属性名称中的字母。

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;
}

这就是我在控制台中获得的(Firefox 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

如何访问数组?

2 个答案:

答案 0 :(得分:2)

您正在访问属性名称,即字符串。 (&#34; line0&#34; &#34; line1&#34;

为了访问属于该属性名称的数组,只需编写代码,如

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;
}

答案 1 :(得分:1)

需要完成操作obj [x]。 请检查代码:

&#13;
&#13;
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);
&#13;
&#13;
&#13;