javascript - 将参数传递给 map()
问题描述
我正在尝试在map()
Array.from () 上使用内置函数,该函数使用 Puppeteer 返回一些元素。
以下是代码:
let res = await page.evaluate(elementPath => {
return Array.from(document.querySelectorAll(elementPath), (cin, index) => {
return {
cs: `state is ${this.s}`, // returns state is undefined
cinemaIndex: index,
cinemaId: cin.getAttribute('data-id'),
cinemaName: cin.getAttribute('data-name'),
cinemaURL: cin.getAttribute('data-url'),
};
}, {
s: 'NSW'
});
}, `div[data-state=${cinemaState}] div.top-select-option a.eccheckbox`, cinemaState);
我无法分配cs
变量s
或cinemaState
.
想知道你有没有解决办法
解决方案
您可以使用以下方法分配s
给语句中的cinemaState
属性:return
cinemaState: this.s,
此外,Array.from()
它有一个内置map
函数,因此您应该map
从内部调用该函数Array.from()
以避免中间数组:
Array.from(arrayLike, mapFn); // good
Array.from(arrayLike).map(mapFn); // bad
cinemaState
最后,您可能希望在模板文字选择器字符串中的属性选择器中使用引号:
[data-state="${cinemaState}"] // good
[data-state=${cinemaState}] // bad
您的最终代码应如下所示:
let res = await page.evaluate(elementPath => {
return Array.from(document.querySelectorAll(elementPath), (cin, index) => {
return {
cinemaState: this.s,
cinemaIndex: index,
cinemaId: cin.getAttribute('data-id'),
cinemaName: cin.getAttribute('data-name'),
cinemaURL: cin.getAttribute('data-url'),
};
}, {
s: 'NSW'
});
}, `div[data-state=${cinemaState}] div.top-select-option a.eccheckbox`, cinemaState);
推荐阅读
- angular - Angular - 表单验证器在初始加载时不起作用
- generics - 有理数对象的整数输入的通用构造函数
- c++ - 使用 SIMD 提高数组的浮点点积的性能
- javascript - 使用 node.js 中的 crypto 使用公共/私有十六进制密钥对加密/解密
- math - 从给定的两组数字生成唯一数字的最佳方法
- python - 基于“Channel LSTM”的基于 LSTM 的 EEG 信号分类架构
- git - git 中的作者/提交者数据不尊重 GIT_CONFIG 变量
- javascript - 如何更改 Tabulator.js 中标题复选框的行为?
- python - 如何通过计算将字符串转换为日期?
- amazon-web-services - 我应该将哪些指标用于警报 HTTPCode_Target_5XX_Count 或 HTTPCode_ELB_5XX_Count?