简体   繁体   English

Javascript中的元素操作

[英]Element-wise Operations In Javascript

I'm doing some physics simulations which of course involve vectors. 我正在做一些物理模拟,当然涉及矢量。 This has become very difficult for me because to the best of my knowledge javascript doesn't support anything like this... 这对我来说变得非常困难,因为据我所知,javascript不支持这样的任何事情......

#with the aid of numpy
>>> a = np.array([1,2,3])
>>> b = np.array([9,2,7])
>>> a+b
array([10,  4, 10])

I've been able to work around this limitation by defining functions that will achieve the same thing, but my formulas end up looking like this: 我已经能够通过定义将实现相同功能的函数来解决这个限制,但我的公式最终看起来像这样:

add(x, add( mult(v,dt), mult(mult( a(x), .5), Math.pow(dt,2))))

So my question is whether there are better ways to achieve this functionality, whether they be features of the language I am unaware of, libraries that address this issue, or more effective ways to deal with it. 所以我的问题是,是否有更好的方法来实现这一功能,无论它们是我不知道的语言的功能,解决这个问题的库,还是更有效的方法来处理它。

Thanks for the help all. 谢谢大家的帮助。

Check out Sylvester . 看看西尔维斯特 I think it might be what you are looking for. 我想这可能就是你要找的东西。

But if you wanted to implement the objects yourself, then it might be better to do a more OOP approach. 但是如果你想自己实现这些对象,那么做一个更多的OOP方法可能会更好。 JavaScript is a prototype-based language, so it different a little bit from other OOP languages, but its still pretty easy to implement your own prototypes. JavaScript是一种基于原型的语言,因此它与其他OOP语言略有不同,但它仍然很容易实现自己的原型。

Something like: 就像是:

Vector = function(items) {
    this.items = items
}

Vector.prototype.add = function(other) {
    var result = []
    for(var i = 0; i < this.items; i++) {
        result.push( this.items[i] + other.items[i])
    }

    return new Vector(result);
}

Vector.prototype.subtract = function(other) { /* code to subtract */ }
Vector.prototype.multiply = function(other) { /* code to multiply */ }

And then use them like this: 然后像这样使用它们:

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

var result = a.add(b)
result.items // [6,2,4]

Or if you wanted to, you could also extend the Array class with some functions with 或者,如果您愿意,还可以使用一些函数扩展Array类

Array.prototype.vectorAdd = function(other) { /* code to add another array as a vector */ };

And call that using 并称之为使用

[1,2,3].vectorAdd([5,0,1])

Hopefully, that might give you a starting point to make your code a little more readable. 希望这可能会为您提供一个使您的代码更具可读性的起点。

Just another note: Unfortunately in this case, JavaScript doesn't support operation overloading so you can't do neat stuff like a+b . 另一个注意事项:不幸的是,在这种情况下,JavaScript不支持操作重载,所以你不能做像a+b这样的整洁的东西。 You'll have to do something like a.add(b) . 你必须做像a.add(b)这样的事情。 but as long you return an appropriate object you can chain methods together. 但只要你返回一个合适的对象,你就可以将方法链接在一起。 Like: 喜欢:

a.add(b).multiply(c).subtract(d);

ps. PS。 the presented code might be a little "off", I just typed it up off the top of my head, so treat it more like pseduocode :) 所呈现的代码可能有点“关闭”,我只是把它打成了我的头顶,所以更像是pseduocode :)

we can use the map function to add array elements: 我们可以使用map函数添加数组元素:

function addvector(a,b){
    return a.map((e,i) => e + b[i]);
}
addvector([2,3,4],[4,7,90]) # returns [6,10,94]

Don't know if this will help, but you can add methods to Array or Number by extending the constructor's .protoype object. 不知道这是否.protoype ,但您可以通过扩展构造函数的.protoype对象来向Array或Number添加方法。

Example: http://jsfiddle.net/9JwLd/ 示例: http //jsfiddle.net/9JwLd/

Array.prototype.add = function( b ) {
    var a = this,
        c = [];
    if( Object.prototype.toString.call( b ) === '[object Array]' ) {
        if( a.length !== b.length ) {
            throw "Array lengths do not match.";
        } else {
            for( var i = 0; i < a.length; i++ ) {
                c[ i ] = a[ i ] + b[ i ];
            }
        }
    } else if( typeof b === 'number' ) {
        for( var i = 0; i < a.length; i++ ) {
            c[ i ] = a[ i ] + b;
        }
    }
    return c;
};
var a = [1,2,3];
var b = [9,2,7];

   // pass an Array
var c = a.add( b );  // [10,4,10]

   // pass a number
var d = a.add( 5 );  // [6,7,8]

The next version of JavaScript (ECMAScript) will likely include Array comprehensions, which may help as well. 下一版本的JavaScript(ECMAScript)可能包括数组理解,这也可能有所帮助。 (Currently supported in SpiderMonkey.) (目前在SpiderMonkey中受支持。)

EXAMPLE: http://jsfiddle.net/dj6Eq/ (Test in newer versions of Firefox.) 示例: http //jsfiddle.net/dj6Eq/ (在较新版本的Firefox中测试。)

var a = [1, 2, 3];
var b = [9, 2, 7];

var c = [a[n]+b[n] for (n in a) ];
var d = [a[n]+5 for (n in a) ];

EDIT: According to the proposal the syntax will be a little different than the current Mozilla implementation of Array comprehensions. 编辑: 根据提案 ,语法将与阵列理解的当前Mozilla实现略有不同。

Using zipWith from lodash ( https://lodash.com/ ): 使用zipWith的zipWith( https://lodash.com/ ):

_.zipWith([1, 2, 3], [9, 2, 7], _.add);
// -> [10, 4, 10]

For just adding arrays in js, you can use this function 只需在js中添加数组,就可以使用此功能

function addArrays(ar1, ar2){
    var ar3 = [];
    for(var i in ar1)
        ar3.push(ar1[i] + ar2[i]);
    return ar3;
}

and then call it like so 然后像这样调用它

var array1 = [1,4,3];
var array2 = [5,3,2];
var array3 = addArrays(array1,array2);
// value of array3 is [6,7,5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM