Javascript 中的元素操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7135874/
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-10-25 23:03:55  来源:igfitidea点击:

Element-wise Operations In Javascript

javascriptvector

提问by danem

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.

感谢大家的帮助。

采纳答案by J. Holmes

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. 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. You'll have to do something like a.add(b). but as long you return an appropriate object you can chain methods together. Like:

另一个注意事项:不幸的是,在这种情况下,JavaScript 不支持操作重载,因此您无法执行诸如a+b. 你必须做类似的事情a.add(b)。但只要你返回一个合适的对象,你就可以将方法链接在一起。喜欢:

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

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 :)

附:所提供的代码可能有点“偏离”,我只是在头顶上输入了它,所以把它当作伪代码来对待:)

回答by Varn K

we can use the map functionto 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]

回答by user113716

Don't know if this will help, but you can add methods to Array or Number by extending the constructor's .protoypeobject.

不知道这是否会有所帮助,但您可以通过扩展构造函数的.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. (Currently supported in SpiderMonkey.)

下一版本的 JavaScript (ECMAScript) 可能会包含数组推导式,这也可能有所帮助。(目前在 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 proposalthe syntax will be a little different than the current Mozilla implementation of Array comprehensions.

编辑:根据提案,语法将与数组理解的当前 Mozilla 实现略有不同。

回答by verse

Using zipWithfrom lodash (https://lodash.com/):

使用zipWith从lodash(https://lodash.com/):

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

回答by Joseph Marikle

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]