Javascript 中的向量类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26785458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:22:37  来源:igfitidea点击:

A Vector Class in Javascript

javascriptarrays

提问by Vishwa

I'm trying to implement a vector object instantiated like below...

我正在尝试实现一个像下面这样实例化的矢量对象......

var a = new Vector([1,2,3]);
var b = new Vector ([2,2,2]);

...and when I do a math operation I need something like this...

......当我做数学运算时,我需要这样的东西......

a.add(b); // should return Vector([4,6,8])

...but my code below returns me just an array

...但我下面的代码只返回一个数组

function Vector(components) {
  // TODO: Finish the Vector class.
  this.arr = components;
  this.add = add;
}

function add(aa) {
  if(this.arr.length === aa.arr.length) {
    var result=[];
    for(var i=0; i<this.arr.length; i++) {
       result.push(this.arr[i]+aa.arr[i]);
    }
    return result;
  } else {
    return error;
  }
}

Please help me out here. Thank you!

请帮帮我。谢谢!

回答by James Thorpe

You need to wrap up your resulting array in a new Vectorobject:

您需要将结果数组包装在一个新Vector对象中:

function Vector(components) {
  // TODO: Finish the Vector class.
  this.arr = components;
  this.add = add;
}

function add(aa) {
  if(this.arr.length === aa.arr.length) {
    var result=[];
    for(var i=0; i<this.arr.length; i++) {
       result.push(this.arr[i]+aa.arr[i]);
    }
    return new Vector(result);
  } else {
    return error;
  }
}

I should note also that you may want to do further reading on creating JavaScript objects, in the area of creating methods (such as your addmethod) on the prototype of the Vectorobject. There are many good tutorials out there.

我还应该指出,您可能希望进一步阅读有关创建 JavaScript 对象的内容,在创建对象add原型的方法(例如您的方法)方面Vector。那里有很多很好的教程。

回答by Eyk Rehbein

The solution by James looks good but it's a bit old-fashioned in my opinion. Here is a way to solve the problem in modern ES6 Javascript Classes.

James 的解决方案看起来不错,但在我看来它有点过时。这是解决现代 ES6 Javascript 类中问题的方法。

class Vector {
  constructor(arr) {
    this.arr = arr;
  }
  add(otherVector) {
    const oa = otherVector.arr;
    if (this.arr.length === oa.length) {
      let res = []
      for(let key in this.arr) {
        res[key] = this.arr[key] + oa[key]
      }
      return new Vector(res)
    }
  }
}