我需要一种简单的方法来将数组中的所有数字(包含在对象中)除以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}];
有什么想法吗?
答案 0 :(得分:4)
这应该适合你:
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]
,从而节省了其他可能的属性。
答案 1 :(得分:2)
for (var i = 0; i < array.length; i++) {
array[i]["x"] /= divisor;
array[i]["y"] /= divisor;
}
答案 2 :(得分: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));
答案 3 :(得分:1)
另一种解决方案,使用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};
});
答案 4 :(得分: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);
答案 5 :(得分: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;
}
答案 6 :(得分: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;
}