JS Array.indexOf 返回错误值

现在我的问题有点奇怪。我在 JS 文件中有一个循环,它循环遍历一个表元素,并应该用数组中的值更新输入字段。


var array = list.replace("[","").replace("]","").split(",");

//9c9bd0f3-9499-4cdc-beaf-3c4d62d3b5a7, 80.0, 15334f50-43eb-46b0-8f7d-1d9011f8b3b5, 20.0

if (array.length > 1) {

    var table = document.getElementById('table');

    for (var r = 1, n = table.rows.length; r < n; r++) {

    //skip first row as that's the head

    //table has 3 rows including head

        var a = table.rows[r];

        var markerId = a.getElementsByTagName("label")[1].id;

        //loop 1: 15334f50-43eb-46b0-8f7d-1d9011f8b3b5

        //loop 2: 9c9bd0f3-9499-4cdc-beaf-3c4d62d3b5a7

        var id = array.indexOf(markerId);

        //loop 1: -1

        //loop 2: 0

        a.getElementsByTagName("input")[0].value = Number(array[(id+1)]);  

    }

}

我的问题是第一个循环返回 -1,即使“markerId”值在数组中。


编辑1:列表变量来自页面显示前的context.put方法,list = [9c9bd0f3-9499-4cdc-beaf-3c4d62d3b5a7, 80.0, 15334f50-43eb-46b0-8f7d-1d9015,f820b.


编辑 2:这是创建和设置列表值的后端代码。


public void doEdit_assignment(RunData data) {

    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    ParameterParser params = data.getParameters();

    String assignmentId = StringUtils.trimToNull(params.getString("assignmentId"));

    Assignment a = getAssignment(assignmentId, "doEdit_assignment", state);

    Set<AssignmentMarker> markers = assignmentService.getMarkers(a);

    List<String> quotas = new ArrayList<String>();

    for (AssignmentMarker marker : markers) {

        quotas.add(marker.getMarkerUserId());

        quotas.add(marker.getQuotaPercentage().toString());

        //add reassign marker select option here

    }

    state.setAttribute(ASSIGNMENT_QUOTA_VALUES, quotas);

    setAssignmentSupplementItemInState(state, a);

}

更何况我不能给你。事实是值在数组中,数组在第二次迭代中起作用,但由于某种原因不是第一次。


子衿沉夜
浏览 228回答 1
1回答

慕沐林林

由于您尚未提供标记,因此table您的代码中的 未定义。list即使没有引号,我也会假设它是一个字符串。所以,var list = '[9c9bd0f3-9499-4cdc-beaf-3c4d62d3b5a7, 80.0, 15334f50-43eb-46b0-8f7d-1d9011f8b3b5, 20.0]'var array = list.replace("[","").replace("]","").split(",");所以,这意味着数组出来是 ..[&nbsp; &nbsp; "9c9bd0f3-9499-4cdc-beaf-3c4d62d3b5a7",&nbsp; &nbsp; " 80.0",&nbsp; &nbsp; " 15334f50-43eb-46b0-8f7d-1d9011f8b3b5",&nbsp; &nbsp; " 20.0"]您的问题可能是双引号后的那些多余空格,因此您的后端代码应该输出list没有多余空格的 ..var list = '[9c9bd0f3-9499-4cdc-beaf-3c4d62d3b5a7,80.0,15334f50-43eb-46b0-8f7d-1d9011f8b3b5,20.0]'// Notice, no spaces between commas.或者,您应该将 Javascript 代码更改为此 ..var array = list.replace("[","").replace("]","").split(",").map(el => el.trim());Map通过循环遍历数组的每个元素来工作,trim从开头/结尾删除空格。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java