将新创建的对象推送到 javascript 数组中时,数组的某些元素与最后一个元素相同,就好像最后一个推送的对象覆盖了旧对象中的某些部分一样。如下所示。
var urlRoot = "http://.../";
var allBooks = [];
var i = 1;
var max = 2; //3;
getPage(i);
function getPage(bookNo) {
if (i > max) {
return;
}
$.ajax({
url: urlRoot + bookNo,
type: 'GET',
cache: false,
success: function(res) {
var html = res.responseText;
allBooks.push(new Book(html));
//allBooks[i - 1] = new Book(html);
console.log(allBooks);
i++;
getPage(i);
}
});
}
当仅推送两个元素和三个元素时,console.log(allBooks) 给出以下结果(标签“EnglishbookHeading”的值发生了变化;但数组“Pages”的内容与最后一个推送的内容相同。):
[Book, Book]
0: Book
EnglishbookHeading: "Revelation"
Hadiths: Array[43]
__proto__: Book
1: Book
EnglishbookHeading: "Belief"
Hadiths: Array[43]
__proto__: Book
length: 2
Array[3]
0: Book
EnglishbookHeading: "Revelation"
Pages: Array[53]
__proto__: Book
1: Book
EnglishbookHeading: "Belief"
Pages: Array[53]
__proto__: Book
2: Book
EnglishbookHeading: "Knowledge"
Pages: Array[53]
__proto__: Book
length: 3
Book.js:
define(["Page"],
function (Page) {
var englishbookHeading;
var thisPages = [];
function Book(html) {
setBook(html);
this.EnglishbookHeading = englishbookHeading;
this.Pages = thisPages;
};
function setBook(html) {
var con = $(html); //Context
...
var chapters = tumHadisler.find('div.chapter');
var index = 0;
chapters.each(function () {
var Page = new Page();
...
thisPages[index] = Page;
index++;
});
}
return Book;
});
页面.js:
define(function () {
function Page() {
this.ChapterId = "";
...
}
return Page;
});