你能永久地在Javascript中添加一个数组吗? [英] Can you permanently add to an array in Javascript?

查看:44
本文介绍了你能永久地在Javascript中添加一个数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我,我对编程很新,尤其是Javascript。我基本上得到了一个如下所示的数组。

Forgive me, I'm very new to programming in general, especially Javascript. I've basically got an array as shown simplified below.

var recipes = [
    { "recipeName":"Recipe1" , "ingredient1":"Recipe1Ingredient1" , "ingredient2":"Recipe1Ingredient2" , "ingredient3":"Recipe1Ingredient3"},
    { "recipeName":"Recipe2" , "ingredient1":"Recipe2Ingredient1" , "ingredient2":"Recipe2Ingredient2" , "ingredient3":"Recipe2Ingredient3"},
];

在一个页面上,用户可以搜索食谱。另一方面,他们可以通过HTML表单向数组添加配方。我有以下内容将新数据推送到数组。

On one page, users can search for recipes. On another, they can add recipes to the array via an HTML form. I have the following which pushes the new data to the array.

recipes.push({"recipeName":newRecipeName , "ingredient1":newIngredient1 , "ingredient2":newIngredient2 , "ingredient3":newIngredient3});

这最初工作正常,但如果我刷新页面或返回查找页面,新的配方已从数组中删除。我希望将新配方永久添加到数组中。

This works fine initially, but if I refresh the page or go back to the find page, the new recipe is removed from the array. I want the new recipe to be added permanently to the array.

我猜这个解决方案不是那么简单,但我一直在调查这个一段时间,做了很多搜索无济于事。任何人都能指出我正确的方向吗?再次为我的经验道歉,我对编程很新。

I'm guessing the solution for this isn't so simple, but I've been looking into this for a while and done a lot of searching to no avail. Can anybody point me in the right direction? Again apologies for my inexperience, I'm very new to programming.

推荐答案

这里需要记住的主要是每次刷新页面时都不知道数据这是在上一页。正如之前的评论中所述,您正在寻找持久存储。这可能是全开(NoSQL / RDBMS)数据库或仅存储在浏览器中的其他半永久形式。

The main thing you need to keep in mind here is that each time the page is refreshed it has no knowledge of the data that was on the previous page. As was mentioned in a previous comment, persistent storage is what you're looking for. This might come in the form of a full-on (NoSQL/RDBMS) database or in some other semi-permanent form stored only within the browser.

你可以开始使用完整的数据库或者如果你想要更轻量级的东西,你可以使用本地存储或< a href =http://www.w3schools.com/js/js_cookies.asp =nofollow noreferrer> cookies 。需要注意的一点是,除非你在服务器端实现某些功能,例如:数据库,否则更改只会持久保存给用户,只要它们不清除缓存即可。

You can either start using a full-on database or if you want something more light weight, you can use local storage or cookies. One thing to note is that, unless you implement something server side, eg: a database, the changes will be persistent only to the user and only so long as they don't clear the cache.

这篇关于你能永久地在Javascript中添加一个数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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