简体   繁体   中英

How to access variable properties in JavaScript

const textContent = await page.evaluate(() => {
  let name = document.querySelector('.listing-name').innerText;
  let street = document.querySelector('.street').innerText;
  let call =  document.querySelector(".ion-android-call").innerText;
  return name + "^" + street + "^" + call;
});

await console.log(textContent.name); 

I want to access here textContent.name but it prints undefined value.

How to access the properties?

Is it possible to access the properties of textContent ?

As Alexander said in his comment in this case textContent is not an object but only a string. If you would like to access the different values without changing it from a string you could use String.split like

console.log(textContent.split('^')[ 0 ])

To automagically split the textContent variable up into an array based on the locations where '^' exist (and also removing them in the process).

If you would like to make it an Object-based approach you would need to modify your code in the call to page.evaluate to fit, something like

const textContent = await page.evaluate(() => {
  let name = document.querySelector('.listing-name').innerText;
  let street = document.querySelector('.street').innerText;
  let call =  document.querySelector(".ion-android-call").innerText;
  return {
    name: name,
    street: street,
    call: call
  }
});

await console.log(textContent.name);

You could also create a single variable Object and set the properties and values inside of it and then return it which would eliminate 2/3 local variables, or use return directly as above but instead set the property values inside of it and use no variables. But whatever is the most readable for you tends to be the best way for you to write your own code, at least until you decide to change your style (or it evolves naturally).

You can expose other properties of local block by returning it.

const textContent = await page.evaluate(() => {
  let name = document.querySelector('.listing-name').innerText;
  let street = document.querySelector('.street').innerText;
  let call =  document.querySelector(".ion-android-call").innerText;
  return 
    {
     content: name + "^" + street + "^" + call,
     name: name ,
     street : street,
     call : call
});

No you can access original result by textContent.content and name using textContent.name .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM