我正在制作一个 javascript 游戏,但(不是基于浏览器的),但我使用的引擎有一个错误,当您退出游戏时,它会删除存储的数组。因此,为了传递这一点,我想将数组存储为变量,然后当您加载游戏时将它们转换回数组。
目前我的游戏只有 1 个数组。 有人建议使用此代码,但它无法正常工作,因为当我运行脚本在不同的行上打印数组的每个元素时,它会在第一行上打印第一个元素,但在第二行上会像这样打印其余元素:元素1,元素2,元素3 这是该人建议的代码:
This code runs every time the arrays are updated. Here, the array is "questsActive", and the var it is stored in is "questsActiveVar".
questsActiveVar = questsActive.toString(); questsActiveVar = questsActiveVar.replace(",", "\",\""); questsActiveVar = "questsActive=new Array(\"".concat(questsActiveVar,"\")");
This runs whenever the game loads; it recreates the array that was deleted
eval(questsActiveVar);
最佳答案
要在 JavaScript 中从字符串
创建数组,您需要使用函数.split()
。这是一个例子:
var someStr = 'item1, item2, item3';
var array = someStr.split(','); // place any character in here to split on
alert(array[0]); // => item1
根据我在您的上下文中的理解,我会简单地保存 questsActiveVar
变量,然后在游戏再次加载时.split()
它。
关于javascript - 将数组存储为变量然后转换回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8726642/