JavaScript array []值与上次添加的值相同

时间:2011-05-01 21:05:12

标签: javascript jstl

forEach中的警报会在插入值时打印这些值,但在forEach之后,数组中的所有值都是相同的。假设我有3个值成功不受控制。我在代码中的某个地方有一个全局数组[],我尝试在函数中更改它,但同样的结果,JSTL会产生问题吗?

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
var jokeArray = [];

                   function ALL(){
                     var object = new Object;
                     var x = new String();
                      <c:forEach var="joke" items="${jokeAllList}">
                           x = '${joke.content}';
                           x = x.replace(/{/g,"\n");
                           x = x.replace(/}/g,"\r"); 
                           object.content = x;
                           object.category = '${joke.category}';
                           object.rate = '${joke.rate}';
                           object.postby = '${joke.postby}';
                           object.votes = '${joke.votes}';
                           object.image = '${joke.image}';
                           jokeArray.unshift(object);
                           alert(jokeArray[0].content);
                      </c:forEach>

why index(s) 0 & 1 & 2 have the same VALUES ? ( Assume there are values and jokeArray.length = 3 )

              alert ( "arr length is " + jokeArray.length);
              alert(jokeArray[0].content);
              alert(jokeArray[1].content);
              alert(jokeArray[2].content);
              alert("done ALL method");

};

alert("done ALL method");

已被警告,因此没有错误

2 个答案:

答案 0 :(得分:0)

我的猜测是因为var object = new Object;var x = new String()在循环之外,你只有一个对象,每个对象的内容都会在循环的后续迭代中被覆盖(即使对象有已被添加到数组中,它仍然可以更改。)

尝试将这两行移动到循环中。你仍然会有一个object JavaScript变量(因为JS不支持范围级变量的方式),但每次迭代都会有一个不同的对象。

答案 1 :(得分:0)

您正在重复使用“对象”变量,请执行

object = new Object();

在你的循环中!