首页 > 解决方案 > EL1012E: 无法索引到空值

问题描述

我在 Thymeleaf 模板中有这段代码

var theList = /*[[${route}]]*/

for (i = 0; i < theList.length; i++) {
    var coordinate = [ /*[[${theList[i].longitude}]]*/ , /*[[${theList[i].latitude}]]*/ ];
    coordinates2.push(coordinate);
}
                        

当对象${route}不为空,而是我通过控制器传递的空列表时:

List<Coordinate> route = new ArrayList<Coordinate>();
model.addAttribute("route", route);

我收到此错误:

org.springframework.expression.spel.SpelEvaluationException: EL1012E: Cannot index into a null value
    at org.springframework.expression.spel.ast.Indexer.getValueRef(Indexer.java:132)
    at org.springframework.expression.spel.ast.Indexer.getValueInternal(Indexer.java:89)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:57)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:87)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:121)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:324)

标签: javaspringspring-mvcspring-bootthymeleaf

解决方案


您不能混合使用 JavaScript 和 Thymeleaf 变量。该变量iJavaScript for 循环 ( for (i = 0; i < theList.length; i++)) 中定义,但您正试图在Thymeleaf表达式中使用它。您需要将它们分开。

var theList = /*[[${route}]]*/ [];

for (i = 0; i < theList.length; i++) {
    var coordinate = [theList[i].longitude, theList[i].latitude];
    coordinates2.push(coordinate);
}

推荐阅读