我试图删除数组中的最后一个元素,但最终会将删除的元素放回列表顶部,并且其他一些元素的列出方式有所不同。
使用 .sort() 方法也是如此。输出显示这句话五次: 托尔斯泰写了《 war 与和平》,吐温写了《哈克贝利·费恩历险记》
var author_title = new Array(5)
author_title[0]="Tolstoy wrote War and Peace";
author_title[1]="Twain wrote Huckleberry Finn";
author_title[2]="Hardy wrote The Return of the Native";
author_title[3]="Dickens wrote A Christmas Carol";
author_title[4]="Uris wrote Exodus";
for(var count=0;count<author_title.length;count++) {
document.write(author_title.pop() + "<br>");
}
for(var count=0;count<author_title.length;count++) {
document.write(author_title.sort()+"<br>");
}
最佳答案
如果您想更改数组,请使用 pop,编写一个相当于 array.length
的变量for
之外循环,然后将变量设置为声明的变量。您必须记住,每次 .pop() 时都会更改数组,从而更改 for-loop
在每次迭代中。另外,<br />
适用于 HTML,因此您可能只是忘记了上面的自关闭标签
var length = array.length;
for( var i = 0; i > length; i++ ) {
document.write( array.pop() + "\n")
}
关于Javascript .pop() 和 .sort() 在 for 循环中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17915205/