【问题标题】:How to save functions in localStorage API HTML5 [duplicate]如何在localStorage API HTML5中保存函数[重复]
【发布时间】:2018-01-19 11:01:46
【问题描述】:

我试图在localStorage 中保存一个数组,但它在数组的一个对象中包含函数(称为 promise),但是当我使用JSON.stringify 将数组转换为字符串时出现问题,显然所有函数都已删除并且当我将字符串解析为JSON Object 时,它没有方法。

/* Example code */

var storage = {
	getListUsers: function(){
		return {
			name: 'name',
			age: 'age'
		}
	},
	active: true,
	data: []
}

var convert = JSON.stringify(storage);
localStorage.setItem('data', convert);

最好的问候。

【问题讨论】:

  • 使用JSON.stringifyreplacer 函数的可选第二个参数 - 以及JSON.parsereviver 函数的可选第二个参数 - 虽然这将是一个挑战
  • “它包含函数(称为 promise)”​​ - 您是在谈论 storage.data 数组中的 promise 吗? (即问题中没有实际显示的承诺?)
  • 我会将逻辑与数据分开,而不是将函数存储在本地存储中。当您的代码块分散在人们的浏览器中时,很难升级您的代码版本。为什么不在对象从 localStorage 重新水化后添加函数(通过扩展或其他方法)?
  • 如果正如 nnnnnn 指出的那样,某些数据是 Promise,那么,a) Promise 不是函数,并且 b) 修复可能知道如何处理异步代码 -保存“Promise”永远不会奏效,因为您无法将有效的 Promise 保存为字符串

标签: javascript json html


【解决方案1】:

观察很少:

  • JSON 中不存在函数。查看官方文档json.org
  • 值可以是双引号中的string,或number,或truefalsenull,或objectarray,但@987654330 @
  • 为什么要在 JSON 对象中使用方法?方法基本上是用来操作数据的。您也可以使用 JSON 对象之外的数据。

您可以使用JSON.stringify替换函数将函数转换为字符串,同时转换为JSON字符串。

演示

var storage = {
	getListUsers: function() {
		return {
			name: 'name',
			age: 'age'
		}
	},
	active: true,
	data: []
}

var json = JSON.stringify(storage, function(key, value) {
  if (typeof value === 'function') {
    return value.toString();
  } else {
    return value;
  }
});

console.log(json);

【讨论】:

  • 如何将此字符串重新转换为以前的函数?
  • 再次将其转换为函数使用 JSON.parse 然后使用 eval 类似的东西 var storage = JSON.parse(storage); storage.getListUsers = eval("(" + storage.getListUsers + ")");
【解决方案2】:

您可以将应该设置在localStorage 的JavaScript 设置为<script> 元素的.textContent,获取要设置在localStorage 的元素的.textContent。然后,您可以在不同的 <script> 元素中设置相同的文本,或者将文本转换为可以发布到其他浏览上下文或服务器的 data URI

<script id="storage">
/* Example code */

var storage = {
  getListUsers: function() {
    return {
      name: 'name',
      age: 'age'
    }
  },
  active: true,
  data: []
}
</script>
<script>
var convert = document.getElementById("storage");

localStorage.setItem("data", convert.textContent);

console.log(localStorage.getItem("data"));    
</script>

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2013-11-25
    • 2013-10-11
    相关资源
    最近更新 更多