。shift()意外修改了原始变量[duplicate]

问题描述 投票:-1回答:1

在我的应用中,我在一个变量(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/

javascript variables shift
1个回答
-1
投票

问题是您使用的是阵列的原始副本。使用Spread syntax (...)

使用浅表副本
...

let cacheCopy = [...cache]
© www.soinside.com 2019 - 2024. All rights reserved.