Home > Blockchain >  Array destructuring producing weird results
Array destructuring producing weird results

Time:10-08

I am using playwrite-rust crate and executing some Js script into chrome. But I am running into something very weird not sure its about JS, browser, or the crate I am using. Anyhow I will share the problem.

Suppose this is the code I am executing through playwright-rust.

async function search(...args) {
    const [session_id, url] = args;
    console.log(args);
    console.log(args.length);
    console.log(url);
}

How its being called in Rust code:

let args = vec![session_id.clone(), build_url];
let json_result = tab
    .evaluate::<Vec<String>, serde_json::Value>(SEARCH, args)
    .await?;

I am expecting to have url and session_id respective value by array destructuring but that's not the case. Have a look here what I get in the browser:

enter image description here

args.length produces 1 and url is undefined. What is wrong here?

CodePudding user response:

You have an array that contains another array. You should use

function search(...args) {
    const [[session_id, url]] = args;
}

or

function search(...args) {
    const [session_id, url] = args[0];
}

or

function search(arg) {
    const [session_id, url] = arg;
}

CodePudding user response:

If Rust calls it like how you mentioned, that is

let args = vec![session_id.clone(), build_url];
let json_result = tab
    .evaluate::<Vec<String>, serde_json::Value>(SEARCH, args)
    .await?;

Then args is an array, therefore your search function should not have this signature :

type search(...args:string):any

but should have this signature :

type search(args:string[]):any

In other words, instead of this function :

function search(...args) {
    // args[0] = [session_id.clone(), build_url];
}

you should have this function :

function search([ session_id, build_url ]) {
   // ...
}
  • Related