调试 JS 的时候发现某些位置很意外地颠倒了顺序,
我存了一个全局变量 store, 每次把 store 存在 history 里边,
那么我觉得 history 里不去操作是不会改变了, 但是.. 却变了.
图片当中第一次查看 history 的最后一项, 第二次的倒数第二项 1 位置发生了颠倒..
图片加载失败的话在这里: http://huaban.com/pins/6503638/zoom/
说到颠倒数组, 我的确有 reverse(store) 这样对 store 进行操作的, 但不该有影响啊.
下面是往 history 数组存储 store 的代码.. 我也试过加 store.concat() , 没效果..
完整在: https://github.com/jiyinyiyong/code_blocks/blob/gh-pages/convert.coffee
editor_mode = on
store = ['\t']
history = [store]
current = 0
history_make = (store) ->
history = history[..current]
console.log ":::", store
history.push store
console.log "###", history[history.length-1]
current+= 1
socket.emit 'sync', store if socket?
window.onload = ->
box = tag 'box'
window.focus()
refresh = (store) ->
console.log store
box.innerHTML = draw store
history_make store.concat()
实在闹不明白是怎么改变掉的.. 求助啊.
回复 (12)
完整代码太长了,你的reverse写到哪里了。是不是先reverse了然后操作store然后再存的。
是的. 大概这个样子.
pgup = ->
if store[0] is cursor then return 'skip'
store = pgup_R store
reverse = (arr) ->
arr.reverse().map (item) ->
if Array.isArray item then reverse item
else item.split('').reverse().join ''
reverse_action = (action) ->
store = reverse store
do action
store = reverse store
pgdown = -> reverse_action pgupgdown = -> reverse_action pgup
-
coffee看不懂,你的代码局部的看不出来。
-
我猜你是不是发生这种情况: 因为都是用的store这个名字,所以你在‘重新赋值’前对store进行了reverse,注意这个时候store指向的值已经reverse了,然后使用了store,之后再对其赋值进行其他操作。
比如:
var array=[1,2]; var array2=array; array.reverse(); array.push(3); print(array); print(array2); array=[3,4]; print(array); print(array2);
编译过去的 reverse_action 函数倒是没有乱,
https://github.com/jiyinyiyong/code_blocks/blob/gh-pages/convert.js#L300
我开始也怀疑, 试过在 history.push(store) 位置, 用了 store.concat() .
照说这样存到 history 里边的数组应该不会继续带指向了..
而且除了 history[0] , 其他都是用像下面这种方式添加到数组的,
store = ['\t'];
history = [store]; // 晕, 第一个反而有问题...
history_make = function(store) {
history.push(store);
}
history_make(store.concat());
我想套了一层新的作用域, 应该也不会再形成错误的指向了呀,
还是这样一层也还是有问题?
@jiyinyiyong 初始化history=[store],所以store.reverse对第一个元素肯定有影响。然后history_make也没看出哪有错啊。要不打个断点调试下吧。
@sumory 断点还真不熟, 是查看运行到断点那行时候的变量值是吗..
我都 console.log() 出来,
但比如 history.push(store); 这行, 只能找到 store , 是不是不能看 history 的?
@jiyinyiyong 运行到下一行时才能看history的值,你可以在你怀疑的方法上打个断点,然后方法内挨步执行,查看里面变量的变化。
@sumory 找到了, 不过还搞不定. 先去找视频学 dev tool 了..
@sumory 找到问题了, 问题出在 .concat()..
本来以为 .concat() 是十足的复制的, 结果嵌套在里边的数组不是复制的...
我对数组递归用一次 arr.map() 进行复制, 然后就没问题了
@sumory 没啊. 只有 history_make(store.concat()); 的问题...
concat 不会改变现有的,返回的是一个副本