【问题标题】:Having trouble translating this ES6 to ES5 including spread syntax无法将此 ES6 转换为 ES5,包括扩展语法
【发布时间】:2016-08-16 17:03:58
【问题描述】:

我正在尝试将以下内容翻译成 ES5,同时学习该语言:

const transitionendFn = ()=> {
    [...this.slider].forEach((el)=> el.className = 'item');
    selectedEl.classList.add('active');
    this.isAnimating = false
}

ES5:

const transitionendFn = function() {
    [].concat(this.slider).
        forEach(function (el) {
            return el.className = 'item';
        });
    selectedEl.classList.add('active');
    this.isAnimating = false
}

我不明白展开部分。

this.slider 包含以下内容:

感谢任何帮助纠正此代码。

我的翻译得到“TypeError: el 未定义”。

【问题讨论】:

  • [...this.slider].forEach 可以翻译为Array.prototype.forEach.call(this.slider, ...[...foo] 成语是一种将类数组对象或可迭代对象转换为数组的方法。
  • [...this.slider] 大致等于Array.from(this.slider)this.slider 应该转换为数组,因为它在这里是可迭代的(可能是也可能不是数组)。
  • ES5 没有const
  • @torazaburo 只是可迭代的,而不是任意的数组。只有Array.from 处理类似数组。

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

请注意:

  • 箭头函数没有this 绑定。传统函数(ES5 中唯一可用的函数)可以,因此您必须将其绑定到所需的值。
  • ES5 没有const 变量。只有var 一个。
  • ES5 没有可迭代对象。我会假设 this.slider 类似于数组。

那么翻译会是这样的

var transitionendFn = function() {
  [].forEach.call(this.slider, function(el) {
    return el.className = 'item';
  });
  selectedEl.classList.add('active');
  this.isAnimating = false;
}.bind(this);

【讨论】:

  • 谢谢@Oriol 和所有参与的人,我正在阅读所有的建议,这么多的信息要在这么短的时间内学习。它奏效了。
猜你喜欢
  • 2019-09-24
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
相关资源
最近更新 更多