zoukankan      html  css  js  c++  java
  • nashorn中js数组转为对象的问题

    背景

    在项目中,使用jdk中的nashorn执行javascript脚本,例如如下脚本片段:

        let ctx = session.ctx;
        ctx.confirm = {
            //车牌划分后的数组
            segments:[],
            //正在确认第几段车牌
            index:0
        };
        let provinceCity = {
            value:ctx.province + ctx.citycode,
            begin:0,
            end:2
        };
        ctx.confirm.segments.push(provinceCity);
        ctx.reply = '是' + provinceCity.value + '开头';
    
        if(ctx.number){
            let number = {
                value:ctx.number,
                begin:2,
                end:2 + ctx.number.length
            };
            ctx.confirm.segments.push(number);
            ctx.segmentSize = 2;
        }else{
            ctx.segmentSize = 1;
        }
    

    通过执行结果可以发现,segments变成了索引值为key的一个对象,这显然不是我们想要的结果:

    {
      "valid": false,
      "confirm": {
        "index": 0,
        "segments": {
          "0": {
            "end": 2,
            "value": "皖a",
            "begin": 0
          },
          "1": {
            "end": 5,
            "value": "123",
            "begin": 2
          }
        }
      }
    }
    

    解决办法

    通过google发现,这是nashorn中的算一个Bug,很多人都提出了相同的问题(https://github.com/intuit/karate/issues/225),其中有人给出了一个解决方案,就是在javascript脚本返回时,调用JSON.stringify(result),具体如下:
    解决方法
    上述方法可以解决数组转为对象,亲测有效

  • 相关阅读:
    codeforces 980A Links and Pearls
    zoj 3640 Help Me Escape
    sgu 495 Kids and Prizes
    poj 3071 Football
    hdu 3853 LOOPS
    hdu 4035 Maze
    hdu 4405 Aeroplane chess
    poj 2096 Collecting Bugs
    scu 4444 Travel
    zoj 3870 Team Formation
  • 原文地址:https://www.cnblogs.com/junjiang3/p/11536278.html
Copyright © 2011-2022 走看看