微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将数组作为函数参数传入或在扩展脚本中使用 array.split

如何解决将数组作为函数参数传入或在扩展脚本中使用 array.split

我正在使用 cep (csinterface) 与扩展脚本通信,我需要在函数中传递一个数组。问题是扩展脚本将我的数组转换为字符串。我想在我的函数中发送一个带分隔符的字符串,但是当我使用 array.split() 时,我收到了一个 evalscript 错误

在 index.js 中

let stringNotes = "2287,3474|2268,3430|2255,3398|2255,3360|2255,3315|2255,3264|2255,3207|2261,3162|2331,3047|2389,3003|2433,2977|2484,2965|2541,2946|2580,2946|2618,2946|2650,2952|2688,2971|2720,2990|2745,3022|2764,3054|2777,3086|2790,3124|2803,3162|2803,3207|2803,3251|2803,3296|2783,3360|2752,3411|2726,3449|2707,3493|2688,3519|2637,3557|2611,3570|2592,3576|2573,3576|2554,3589|2548,3589|2541,3589|2535,3589|2529,3589|2516,3589|2510,3589|2503,3583|2497,3576|2497,3557|2497,3551|2497,3525|2497,3512|2497,3493|2490,3481|2490,3455|2478,3442|2478,3423|2478,3417|2471,3398|2465,3391|2459,3372|2452,3366|2446,3366*2401,3328|2389,3321|2382,3321|2376,3321|2369,3315|2350,3309|2344,3302";

stringNotes = stringNotes.split("*");

for(let i=0;i<stringNotes.length;i++) {   stringNotes[i] = stringNotes[i].split("|");   for(let j=0;j<stringNotes[i].length;j++) {
    stringNotes[i][j] = stringNotes[i][j].split(",");
    stringNotes[i][j][0] = parseInt(stringNotes[i][j][0]);
    stringNotes[i][j][1] = parseInt(stringNotes[i][j][1]);   }  }

console.log(stringNotes);

for(let i=0;i<stringNotes.length;i++) {   //Call evalscript and send my list to evalscript   csInterface.evalScript(`DrawShape('${JSON.stringify(stringNotes[i])}')`,function(res){console.log(res)}); }

注意:index.js 中我的数组 stringNotes 的 console.log 正确显示数组

在 index.jsx 中

function DrawShape(arr) 
{
    return arr[0];
}

控制台中的异常输出: [2287,3474] [2401,3328]

结果: [ [

感谢您的帮助!

解决方法

您的模板文字确实会生成一个单引号字符串文字,并传递给 [2,6,12,18,41,43,55,65,72]

相反,请确保它不通过“123,132,322”,而是通过 [123,322]。简单的部分是您应该删除那些单引号。然后将您的数组转换为 JSON。

请参阅下面的评估内容的差异。在这里,我不调用评估器,而只是显示它可以使用的内容:

DrawShape

,

这取决于你是否想要一个整数数组,如果它的情况使用 JSON.parse:

var array = JSON.parse("[" + string + "]");

如果你想要一个字符串数组,你可以使用 .split() 方法并得到这样的结果:

["0","1"]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。