代码结束后,如何将输入永久存储到数组中? [英] How can I store input into an array permanently after my code ends?

查看:127
本文介绍了代码结束后,如何将输入永久存储到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是数组 nameData ,我想知道是否有某种方法可以将用户的输入保存到给定的数组中,即使我的代码运行完后也是如此.我想这反映了我在空闲时间做的事...

Below is the array nameData and I want to know if there is some way to save the user's input into the given array even after my code is finished running. I guess that this reflects upon what i do in my free time...

var nameData = ["Nik"];
var Name = prompt("PLEASE ENTER YOUR NAME:");
if (Name !== null){
 alert("Hello " + Name + "!");
nameData.push(Name); 
} 

for (var i = 0; i < nameData.length; i++) {
console.log(nameData[i]);
}

推荐答案

在JavaScript中运行的代码不是持久性的.程序完成后,将丢弃内存中的所有值.您需要使用服务器端语言将值保存到磁盘或将其存储在数据库中.

Code that runs in JavaScript it not persistent. Once the program is finished, all values in memory are discarded. You need to save the value to disk or store it in a database using a server-side language.

您可以使用以下命令导出阵列:

You can export the array with:

var savedFile_JsonStringData = JSON.stringify(nameData);

并将其字符串内容存储在文件或数据库中.

and store its string contents in a file or database.

然后,要导入数据,加载保存的文件并将其字符串表示形式转换回数组:

Then, to import the data, load the saved file and convert its string representation back into an array:

var nameData = JSON.parse(savedFile_JsonStringData);


本地存储

正如其他人所指出的,如果您不需要数据长时间停留,则可以使用临时存储方法.


Local Storage

As others have noted, a temporary storage method may work if you don't need the data to hang around for too long.

Window.sessionStorage 提供以下内容:

sessionStorage属性允许您访问会话存储对象. sessionStorage类似于 localStorage ,唯一的不同是localStorage中存储的数据没有设置到期时间,而sessionStorage中存储的数据在页面会话结束时被清除.页面会话的持续时间只要浏览器处于打开状态,并且在页面重新加载和还原后仍然存在.在新标签页或窗口中打开页面将导致启动新会话.

The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

最低浏览器版本支持

Feature        | Chrome | Firefox | IE | Opera | Safari
---------------+--------+---------+----+-------+-------
localStorage   | 4      | 3.5     | 8  | 10.50 | 4
sessionStorage | 5      | 2       | 8  | 10.50 | 4

示例

// Save data to sessionStorage
sessionStorage.setItem('myKey', JSON.stringify(nameData));

// Get saved data from sessionStorage
var nameData = JSON.parse(sessionStorage.getItem('myKey'));

这篇关于代码结束后,如何将输入永久存储到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆