繁体   English   中英

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

[英]Failing accessing array which is property of an object in 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;
}

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

如何访问阵列?

您正在访问属性名称,即字符串。 “line0”“line1”

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

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

操作需要完成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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM