如何减去数组[0]和[1]等等

时间:2017-01-10 04:59:47

标签: javascript

我有两个数组:

var array = [100,200,300,400];
var another = [50,100,150,200];

说我不知道​​阵列有多长,但知道它们的长度相同。如何减去相应的元素?

2 个答案:

答案 0 :(得分:2)

使用array.map,如下所示

var arra = [100, 200, 300, 400];
var another = [50, 100, 150, 200];

var diff = arra.map(function(v, i) {
  return v - another[i]
});

console.log(diff)

答案 1 :(得分:0)

试试这个



<!DOCTYPE html>
<html>

<body>

    <script>
        var arra = [100, 200, 300, 400];
        var another = [50, 100, 150, 200];
        var diff = [];
        for (var i = 0; i < arra.length; i++) {
            diff[i] = arra[i] - another[i];
            console.log(diff[i]);
        }
    </script>
</body>

</html>
&#13;
&#13;
&#13;

只需减去相应的位置。