简体   繁体   English

将 Javascript 数组分配给变量会导致项目从数组中删除

[英]Assigning Javascript array to variable is causing items to drop from array

I am experiencing a weird problem where assigning an array to a variable is causing some of the items in the array to be removed.我遇到了一个奇怪的问题,将数组分配给变量会导致数组中的某些项目被删除。 This could potentially be related to Vue.js as well.这也可能与 Vue.js 有关。

I am storing an array of data in localStorage as a string ( since that is all localStorage accepts ).我将数据数组作为字符串存储在 localStorage 中(因为这是所有 localStorage 接受的)。 When the user clicks a button within the app it runs a Vue function checking to see if localStorage has a particular key and if so I am assigning that key to a variable 'localCards' within the function.当用户单击应用程序中的按钮时,它会运行 Vue function 检查 localStorage 是否有特定的键,如果有,我将该键分配给 function 中的变量“localCards”。 When the localStorage data gets assigned to the variable it is dropping some of the items in the array.当 localStorage 数据被分配给变量时,它正在删除数组中的一些项目。 Below is a sample of the code for a better understanding:下面是一个代码示例,以便更好地理解:

console.log( JSON.parse(localStorage.getItem('localCards')) );
// Returns the complete array
let localCards = JSON.parse(localStorage.getItem('localCards'));
console.log( localCards );
// Returns the first two items in the array

Any idea why assigning the data to a variable is dropping some of the items?知道为什么将数据分配给变量会删除一些项目吗?

It turns out that this was happening because the array was being mutated later in the code.事实证明,之所以发生这种情况,是因为该数组后来在代码中发生了变异。 I was not aware that it would affect logging prior to the mutation as pointed out by @skirtle in the comments above.正如@skirtle 在上面的评论中指出的那样,我不知道它会影响突变之前的日志记录。

i guess you should declare your variable first...as an array;我想你应该首先声明你的变量......作为一个数组; then parse it然后解析它

var localCards =[];
localCards =JSON.parse(localStorage.getItem('localCards'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM