Why does Array.prototype.filter() throw an error in Magnolia JavaScript models?

若如初见. 提交于 2020-02-26 00:52:27

问题


I'm attempting to filter a FreeMarker list in a Magnolia JavaScript model using Array.prototype.filter().

List

[#assign list = [1, 2, 3]]

Model

var Model = function() {
  this.filterList = function(list) {
    return list.filter(function(item) {
      return item === 2
    });
  }
};

new Model();

Usage

${model.filterList(list)}

However, I get the following error.

Caused by: jdk.nashorn.internal.runtime.ECMAException: TypeError: list.filter is not a function

Nashorn was implemented using ECMAScript-262 5.1.

The Nashorn JavaScript engine was first incorporated into JDK 8 via JEP 174 as a replacement for the Rhino scripting engine. When it was released, it was a complete implementation of the ECMAScript-262 5.1 standard. — JEP 335: Deprecate the Nashorn JavaScript Engine

Why despite the fact that Nashorn follows ECMAScript-262 5.1 do I get an error when using Array.prototype.filter()?


回答1:


The FreeMarker list you are passing to the model is a sequence, not a JavaScript array.

Sequence (3)
  0 = 1 (BigDecimal)
  1 = 2 (BigDecimal)
  2 = 3 (BigDecimal)

To solve the issue, convert the FreeMarker list you are passing to the model to a JavaScript array using Java.from(). For example:

var Model = function() {
  this.filterList = function(list) {
    return Java.from(list).filter(function(item) {
      return item === 2
    });
  }
};

new Model();


来源:https://stackoverflow.com/questions/60269057/why-does-array-prototype-filter-throw-an-error-in-magnolia-javascript-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!