0

我需要一种简单的方法来将数组中的所有数字(包含在对象中)除以 javascript 中的变量(没有 jquery 或其他库):

var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];

预期结果:

[{"x":0,"y":1},{"x":1,"y":2},{"x":2,"y":3}];

有任何想法吗 ?

4

7 回答 7

5

这应该为你做:

var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];

for(var i = 0, length = array.length; i < length; i++){
    array[i] = {'x':array[i].x/divisor,'y':array[i].y/divisor};
}

如果您将来可能扩展对象,您可能希望这样做,而不是:

for(var i = 0, length = array.length; i < length; i++){
    array[i].x /= divisor;  // `a[i].x /= d` is shorthand for `a[i].x = a[i].x / d`
    array[i].y /= divisor;
}

这样做的好处是它不会覆盖array[i],从而节省可能的其他属性。

于 2013-02-08T15:34:09.580 回答
3

另一个解决方案,使用map和回调:

var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];

array = array.map(function(v){
  return {x: v.x / divisor, y: v.y / divisor};
});  
于 2013-02-08T15:35:42.667 回答
2
for (var i = 0; i < array.length; i++) {
    array[i]["x"] /= divisor;
    array[i]["y"] /= divisor;
} 
于 2013-02-08T15:35:58.717 回答
2

这里的鸿沟很深。

var divideBy = function(object, divider) {
    if (typeof(object) == 'number') return object/divider;
    for (var i in object) {
        if (object.hasOwnProperty(i)) {
            object[i] = divideBy(object[i], divider);
        }
    }
    return object;
}

var obj = [{a: 16, b: 32}, {c: 0, d: 48, e: 160}];
console.log(divideBy(obj, 16));
于 2013-02-08T15:40:29.620 回答
1

在这里,它是一个函数,因此您可以重复使用它。它不限于每个对象只有 2 个变量。

function divideArray(array, divisor) {
    var i = array.length, a, k;
    while (i) { // loop over each item in array
        a = array[--i];
        for (k in a) { // loop over each key in object
            if (a.hasOwnProperty(k)) { // ignore inherited keys
                a[k] = a[k] / divisor; // calculate
            }
        }
    }
    return array;
}

// use with your example
var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];
array = divideArray(array, divisor);
于 2013-02-08T15:37:21.000 回答
0

尝试这个

        var divisor = 16;
        var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];
        var i=0;
        for(i=0;i<array.length;i++)
        {
            array[i]["y"]=array[i]["y"]/divisor;
            array[i]["x"]=array[i]["x"]/divisor;
        }
于 2013-02-08T15:35:17.923 回答
0
var divisor = 16;
    var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];
    var i=0;
    for(i=0;i<array.length;i++)
    {
        array[i]["y"]=array[i]["y"]/divisor;
        array[i]["x"]=array[i]["x"]/divisor;
    }
于 2017-08-16T14:43:44.763 回答