gpt4 book ai didi

javascript - 如何在javascript中对两个对象的属性求和

转载 作者:行者123 更新时间:2023-12-02 08:05:10 25 4
gpt4 key购买 nike

我正在尝试做一些我不记得/找不到在 javascript 中是否可行的事情。

我有一个对象构造函数“Point”,我想知道是否可以像下面这样对两个不同的对象求和。

function Point(x, y) {
this.x = x;
this.y = y;
}

a = new Point(1,2);
b = new Point(2,3);
c = a+b;


console.log('a: ', a)
console.log('b: ', b)
console.log('c: ', c)

a = Point {x: 1, y: 2}
b = Point {x: 2, y: 3}
Expected result: c = Point {x: 3, y: 5}

最佳答案

function sumOfObjects(Obj1, Obj2){
var finalObj = {};
this.keys(Obj1).forEach(value =>{
if (Obj2.hasOwnProperty(value)) {
finalObj[value] = Obj1[value] + Obj2[value]
}
});
return finalObj;
}

关于javascript - 如何在javascript中对两个对象的属性求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com