- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如下所示,我制作了一个简单的高分数组,保存到本地存储并添加到用户提示中。
作为一个独立的文件,它本身就很好用。或者至少看起来是这样。
但是,当我尝试将它集成到我的大型应用程序中时,我的全局变量 allScores 似乎遇到了范围问题。数组的长度保持为 0。我检查了是否有任何重复的变量,但我没有。
我一直在尝试阅读有关函数提升和作用域的内容。我不确定为什么下面的代码作为一个独立的文件工作,但是当我将它集成到我的更大的应用程序中时,我遇到了范围问题。
我应该如何以不同的方式来做这件事?由于我是 JavaScript 的新手,所以我的最佳实践很可能已经过时了。感谢您的指导。谢谢。
var allScores = [];
function saveScore() {
if (allScores.length === 0) {
allScores[0]= prompt('enter score', '');
localStorage ['allScores'] = JSON.stringify(allScores);
}
else if (allScores.length < 3) {
var storedScores = JSON.parse(localStorage ['allScores']);
storedScores = allScores;
var injectScore = prompt('enter score', '');
allScores.push(injectScore);
allScores.sort(function(a, b) {return b-a});
localStorage ['allScores'] = JSON.stringify(allScores);
}
else {
var storedScores = JSON.parse(localStorage ['allScores']);
storedScores = allScores;
var injectScore = prompt('enter score', '');
allScores.pop();
allScores.push(injectScore);
allScores.sort(function(a, b) {return b-a});
localStorage ['allScores'] = JSON.stringify(allScores);
}
document.getElementById('readScores').innerHTML = allScores;
}**
最佳答案
由于您在问题中提到了最佳实践,因此我重构了您的代码以展示一些可能在未来对您和其他人有所帮助的实践。此重构中使用的概念列表如下。
var saveScore = (function () { /* Begin IIFE */
/*
The variables here are scoped to this function only.
They are essentially private properties.
*/
var MAX_ENTRIES = 3;
/*
Move the sorting function out of the scope of saveScore,
since it does not need any of the variables inside,
and possibly prevent a closure from being created every time
that saveScore is executed, depending upon your interpreter.
*/
function sorter(a, b) {
return b - a;
}
/*
As far as your example code shows, you don't appear to need the
allScores variable around all the time, since you persist it
to localStorage, so we have this loadScore function which
pulls it from storage or returns a blank array.
*/
function getScores() {
var scores = localStorage.getItem('scores');
return scores ? JSON.parse(scores) : [];
/*
Please note that JSON.parse *could* throw if "scores" is invalid JSON.
This should only happen if a user alters their localStorage.
*/
}
function saveScore(score) {
/* Implicitly load the scores from localStorage, if available. */
var scores = getScores();
/*
Coerce the score into a number, if it isn't one already.
There are a few ways of doing this, among them, Number(),
parseInt(), and parseFloat(), each with their own behaviors.
Using Number() will return NaN if the score does not explicitly
conform to a textually-represented numeral.
I.e., "300pt" is invalid.
You could use parseInt(score, 10) to accept patterns
such as "300pt" but not anything with
leading non-numeric characters.
*/
score = Number(score);
/* If the score did not conform to specifications ... */
if (isNaN(score)) {
/*
You could throw an error here or return false to indicate
invalid input, depending on how critical the error may be
and how it will be handled by the rest of the program.
If this function will accept user input,
it would be best to return a true or false value,
but if a non-numeric value is a big problem in your
program, an exception may be more appropriate.
*/
// throw new Error('Score input was not a number.');
// return false;
}
scores.push(score);
scores.sort(sorter);
/*
From your code, it looks like you don't want more than 3 scores
recorded, so we simplify the conditional here and move
"magic numbers" to the header of the IIFE.
*/
if (scores.length >= MAX_ENTRIES) {
scores.length = MAX_ENTRIES;
}
/* Limiting an array is as simple as decreasing its length. */
/* Save the scores at the end. */
localStorage.setItem('scores', JSON.stringify(scores));
/* Return true here, if you are using that style of error detection. */
// return true;
}
/* Provide this inner function to the outer scope. */
return saveScore;
}()); /* End IIFE */
/* Usage */
saveScore(prompt('Enter score.', ''));
如您所见,通过将分数处理逻辑封装在此函数上下文中,几乎没有任何东西可以在不使用接口(interface)的情况下篡改内部。理论上,您的 saveScore
函数可以被其他代码取代,但是 IIFE
上下文的内部只对那些有权访问的人是可变的。虽然有 no constants 还 standardized ECMAScript ,这种模块模式的方法论提供了一个具有可预测结果的体面的解决方案。
IIFE
,一个立即调用的函数表达式,用于创建我们的模块DRY
, 不要重复自己:代码重用关于javascript - 范围或功能提升问题?我不知道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350380/
在本教程中,您将通过示例学习 JavaScript。 JavaScript 中的提升是一种在声明之前可以使用函数或变量的行为。例如, // using test before declarin
我正在学习javascript提升功能,发现下面的代码真的很困惑: var a = 1; function b() { a = 10; return; function a()
作为一个JS学习者,我发现了一件很有趣的事情,考虑下面的代码。 this.init = function (e) { var container = e.container;
Quasiquotes 的 Scala 文档在解释 Lifting 时提到了这一点: One can also combine lifting and unquote splicing: scala
我是新来的。到目前为止,我一直在使用 MVC 模型并使用基本的 session 管理模型,即在 session 中存储一个 token 并检查每个请求。 我正在尝试对lift做同样的事情,但我的 se
我当前使用的是Elasticsearch 2.4版,希望根据查询时间的增加或加权,根据我称为“类型”的字段对结果集进行微调。 例如 如果字段“类型”的值为“船”,则将权重或增强值增加4 如果字段“类型
一年多以来,我一直在大量使用 lift、return 以及 EitherT、ReaderT< 等构造函数,等等。我读过《Real World Haskell》、《Learn You a Haskell
我浏览了电梯的MegaProtoUser遇到这种结构:??("Last Name")。谁能解释一下,这是什么意思? 谢谢解答 最佳答案 它是在对象 S 上定义的: def ??(str : Strin
我有一个Solr索引,每个文档都是一个Event的信息。在我的架构中,Schedule 是日期类型的多值字段。我想知道是否可以使用计划日期来增加文档(多值字段中的任何日期)在未来并且最接近当前日期?我
作为测试,我正在尝试使用设计人员友好的模板在 lift 中创建一个表单。我正在使用 Lift 2.5 我已经设法使用 toForm 创建了一个工作表单,但我只是在探索所有可能的方法。 我的 html
如果这个问题已经被问到,我深表歉意。 是否可以清除已经设置的条件变量? 下面是我想要实现的详细信息: void worker_thread { while (wait_for_conditio
尝试学习Js,无法理解为什么DOM元素没有获取到值: var Car = function(loc) { var obj = Object.create(Car.prototype); obj
我想知道吊装。我知道如果全局函数名称与全局变量相同,函数会覆盖变量的名称。是吗? 这是我的代码。 (function() { console.log('console.log#1 ' + glob
这个问题已经有答案了: var functionName = function() {} vs function functionName() {} (41 个回答) 已关闭 7 年前。 在javas
我正在开发 Windows 资源管理器 namespace 扩展。我的应用程序是explorer.exe在某个时候加载和使用的动态库。我需要我的 DLL 在 C:\中创建文件,有时在其他需要提升才能执
背景: GitHub 属于客户。我们团队中有一些新手,他们有时会错过基本的命名约定和其他编码协议(protocol)。所以,如果哪位前辈想在内部review,除了创建PR,别无他法。但是这个 PR 对
我们需要在运行时更改 HKEY_LOCAL_MACHINE 的一些设置。 如果需要在运行时,是否可以提示 uac 提升,或者我是否必须启动第二个提升的进程来完成“肮脏的工作”? 最佳答案 我会以提升的
看着Haskell文档,提升似乎基本上是 fmap 的概括,允许映射具有多个参数的函数。 Wikipedia然而,关于提升的文章给出了不同的观点,根据类别中的态射来定义“提升”,以及它如何与类别中的其
ggplot2 package 很容易成为我用过的最好的绘图系统,除了对于较大的数据集(约 50k 点)性能不是很好。我正在研究通过 Shiny 提供网络分析,使用 ggplot2作为绘图后端,但我对
是否可以提升 powershell 脚本的权限,以便没有管理员权限的用户可以运行该脚本?我们的网络管理员正在尝试寻找更省时的方法来完成某些任务,目前他们必须使用远程桌面...使用 PS 脚本将其自动化
我是一名优秀的程序员,十分优秀!