在我的应用中,我在一个变量(cache
)中缓存了一个数组。当我将缓存的数组复制到新变量(cacheCopy
)并使用cacheCopy.shift()
对其进行更改时,cache
也被意外更改。
如何避免这种情况?我希望原始的cache
保持不变,以便应用程序的其他部分可以使用它。此行为与.shift()
有关吗?
示例:
let cache = ['bird', 'cat', 'elephant', 'rabbit', 'monkey']
let cacheCopy = cache
let continueFiltering = true
// Look for "rabbit" in cacheCopy
while (continueFiltering) {
let animal = cacheCopy.shift()
if (animal === "rabbit") {
continueFiltering = false
}
}
console.log('Why was the original cache modified?')
console.log(cache)
工作示例(在单击“测试”之前打开控制台):https://jsfiddle.net/s4z6u7fv/