-
函数式编程
如果在对象创建期间想要一个完全可用的对象,请使用 Function 对象。let arrayObj = [new function(){ this.number1 = 1; this.number2 = 2; this.sum = sum(this.number1 , this.number2)}]// minor edit to return the sum instead of returning the result of the console logfunction sum(n1, n2) { console.log(n1 + n2); return n1 + n2;}for (let i in arrayObj){ console.log(arrayObj[i])}但是,如果您以后需要此功能,并希望所有这些对象都可以访问它,那么请停止使用匿名对象并创建一个实际的类或原型。原型:function Point(number1, number2){ this.number1 = number1; this.number2 = number2;}Point.prototype.sum = function(){ return this.number1 + this.number2;}let arrayObj = [ new Point(1,2), new Point(3,4), new Point(15,30)];for (let i in arrayObj){ console.log(arrayObj[i].sum())}班级:class Point { constructor(number1, number2){ this.number1 = number1; this.number2 = number2; } get sum(){ return this.number1 + this.number2; }}let arrayObj = [ new Point(1,2), new Point(3,4), new Point(15,30)];for (let i in arrayObj){ console.log(arrayObj[i].sum)}
-
吃鸡游戏
您可以在遍历对象时将该属性添加到对象。const arrayObj = [{ number1: 1, number2: 2,}];function sum(n1, n2) { return n1 + n2;}for (let i in arrayObj){ arrayObj[i].sum = sum(arrayObj[i].number1, arrayObj[i].number2) console.log(arrayObj[i])}
-
茅侃侃
有一个简单的解决方案。您可以在 sum 属性中放置一个即时函数,并在该函数下,通过将对象的其他所需值转换为变量来发送它们。见下文:function sum(n1, n2) { return n1 + n2;}const arrayObj = [{ 'number1': 1, 'number2': 2, 'sum': function () { let num1 = this.number1, num2 = this.number2; return sum(num1, num2); } }];console.log(arrayObj.sum())
-
隔江千里
对于这个问题,我找到了另一个有趣的解决方案(我不记得是在哪里找到的。)。使用javascript 的getter 函数可以轻松解决问题。您可以直接在对象中使用它来使用外部函数。如果对象的属性(键)使用外部函数来获取值,并且它的行为必须像普通的“键:值”对(不是方法/函数),那么 getter 函数是最好的使用方法得到价值。function sum(n1, n2) { return n1 + n2;}const arrayObj = { get sum() {return sum(this.number1, this.number2)}, number1: 1, number2: 2, number3: 4, get totalsum() {return sum(this.sum, this.number3)} //using the sum property (that used external function) in another property. };console.log(arrayObj);console.log('the sum of '+arrayObj.number1+' & '+arrayObj.number2+' is: '+arrayObj.sum); console.log('the sum of '+arrayObj.sum+' & '+arrayObj.number3+' is: '+arrayObj.totalsum);