【发布时间】:2016-07-03 06:26:51
【问题描述】:
我目前正在研究数据结构,并一直在探索 javascript。我一直在写一个反向数组就地方法来解决这个问题。我查看了有关数组对象、Object.prototype 和函数对象的文档,但我找不到正在发生的事情的答案。也许我有一个逻辑错误,这里是代码:
//Reverse Array in Place Exercise
Array.prototype.tRev = function()
{
var nRay = this.valueOf(); //copy current instance of array
for (var x = 0,y = this.length-1; x < this.length; x++,y--)
{
this[x] = nRay[y]; //switch array element with copy of nRay (original elements)
}
}
这个方法给了我不熟悉的结果。
var z = [1,2,3,4,5];
var z1 = [343,32423,2434,4,5,5,3];
var z2 = ['hello','hi','goodbye'];
z.tRev(); //console -- > Array [ 5, 4, 3, 4, 5 ]
z1.tRev(); //console -- > Array [ 3, 5, 5, 4, 5, 5, 3 ]
z2.tRev(); //console -- > Array [ "goodbye", "hi", "goodbye" ]
为了尝试调试,我编写了几个 console.logs 来跟踪当前实例和复制数组中的迭代器和数组元素。
var z = [1,2,3,4,5];
z.tRev();
undefined
current x is = 1 new copy of y is = 5
x iterator is = 0 z iterator is = 4
new x is = 5 old copy of y is = 5
current x is = 2 new copy of y is = 4
x iterator is = 1 z iterator is = 3
new x is = 4 old copy of y is = 4
current x is = 3 new copy of y is = 3
x iterator is = 2 z iterator is = 2
new x is = 3 old copy of y is = 3
current x is = 4 new copy of y is = 4
x iterator is = 3 z iterator is = 1
new x is = 4 old copy of y is = 4
current x is = 5 new copy of y is = 5
x iterator is = 4 z iterator is = 0
new x is = 5 old copy of y is = 5
任何见解将不胜感激。
【问题讨论】:
标签: javascript arrays object data-structures iteration