我需要一种简单的方法来将数组中的所有数字(包含在对象中)除以 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}];
有任何想法吗 ?
我需要一种简单的方法来将数组中的所有数字(包含在对象中)除以 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}];
有任何想法吗 ?
这应该为你做:
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]
,从而节省可能的其他属性。
另一个解决方案,使用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};
});
for (var i = 0; i < array.length; i++) {
array[i]["x"] /= divisor;
array[i]["y"] /= divisor;
}
这里的鸿沟很深。
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));
在这里,它是一个函数,因此您可以重复使用它。它不限于每个对象只有 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);
尝试这个
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;
}
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;
}