简体   繁体   English

如何更改ES5-> ES8 JS函数语法?

[英]How to change ES5 -> ES8 JS function syntax?

I try to change this (working well) function to be able to run with node + ES8 (without the keyword function), but I can't figure out how to do this. 我尝试更改此功能(运行良好)以使其能够与node + ES8一起运行(不使用关键字功能),但是我不知道该怎么做。

window.getElementsByXPath = function getElementsByXPath(expression, scope) {
    scope = scope || document;
    var nodes = [];
    var a = document.evaluate(expression, scope, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0; i < a.snapshotLength; i++) {
        nodes.push(a.snapshotItem(i));
    }
    return nodes;
};

(this is a file sourced from node.js to use with puppeeter + chrome headless) (这是一个来自node.js的文件,可用于puppeeter + chrome headless)

Just remove the keyword function and function name as follow: 只需删除关键字function和函数名称,如下所示:

window.getElementsByXPath =  (expression, scope) => {
  scope = scope || document;
  var nodes = [];
  var a = document.evaluate(expression, scope, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  for (var i = 0; i < a.snapshotLength; i++) {
    nodes.push(a.snapshotItem(i));
  }
  return nodes;
};

This is called: Arrow function. 这称为:箭头功能。

Resource 资源

Use the arrow function syntax: var foo = (param) => { // Do stuff } 使用箭头函数语法: var foo = (param) => { // Do stuff }

With your code: 使用您的代码:

window.getElementsByXPath = (expression, scope) => {
    scope = scope || document;
    var nodes = [];
    var a = document.evaluate(expression, scope, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0; i < a.snapshotLength; i++) {
        nodes.push(a.snapshotItem(i));
    }
    return nodes;
};

If you want to go all the way, you could use the iterator type instead of snapshot, make an immediately executing generator, and use the spread and short arrow expression syntax. 如果要一直使用,可以使用迭代器类型而不是快照,制作立即执行的生成器,并使用散布和短箭头表达式语法。

window.getElementsByXPath = (expression, scope) =>
    [...(function * (iter, node) {
        while (node = iter.iterateNext()) yield node;
    })(document.evaluate(expression, scope || document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null))];

Not that this makes it more readable though... 但这并不意味着它更具可读性...

The function keyword reappears, as generators can currently not be written with arrow syntax. 由于当前无法使用箭头语法编写生成器,因此将再次出现function关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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