小编Jas*_*lly的帖子

我如何在JavaScript中执行操作就像在Java流中进行操作管道一样?

在Java 8中,当我一个接一个地链接方法时,使用流以流水线方式执行操作.

例:

List<Integer> nums = Arrays.asList(1,2,3,4,5,6);    
nums.stream().map(x->{
    x = x * x;
    System.out.println("map1="+x);
    return x;
}).map(x->{
    x = x * 3;
    System.out.println("map2="+x);
    return x;
}).forEach(x-> System.out.println("forEach="+x));
Run Code Online (Sandbox Code Playgroud)

输出: -

map1=1
map2=3
forEach=3
map1=4
map2=12
forEach=12
map1=9
map2=27
forEach=27
map1=16
map2=48
forEach=48
map1=25
map2=75
forEach=75
map1=36
map2=108
forEach=108
Run Code Online (Sandbox Code Playgroud)

但是当我在javascript中尝试类似时.结果是不同的.在javascript中,第一个操作完成,然后执行第二个操作.例如: -

var nums = [1,2,3,4,5,6 ];
nums.map(x => {
  x = (x * x);
  console.log('map1='+x);
  return x;})
  .map(x => {
  x = x * 3;
  console.log('map2='+x);
  return x;})
  .forEach(x=> console.log('forEach='+x));
Run Code Online (Sandbox Code Playgroud)

输出: - …

javascript java

17
推荐指数
2
解决办法
1388
查看次数

标签 统计

java ×1

javascript ×1