简体   繁体   English

创建一个计数器 - Javascript

[英]Creating a Counter - Javascript

My apologies in advance if this is a very basic question/answer - I have searched, and am "old" learning for the first time and have found myself a little lost.如果这是一个非常基本的问题/答案,我提前道歉 - 我已经搜索过,并且是第一次“老”学习并且发现自己有点迷路。

It's my first time coding, and basically I have an array (lets say fruits), I've been able to create it displaying the array and shuffling that array on click - which is exactly what I wanted (yay go me).这是我第一次编码,基本上我有一个数组(假设是水果),我已经能够创建它来显示数组并在单击时洗牌该数组 - 这正是我想要的(是的 go 我)。

Now I am trying to have the ability to keep track of how many times I have clicked the shuffle button = before I either click reset, leave the page or refresh the page in which the counter resets.现在,我试图能够跟踪在单击重置、离开页面或刷新计数器重置的页面之前,我单击了随机播放按钮 = 的次数。

This is where my trouble lays.这就是我的麻烦所在。 I am having trouble 'inter-twining' the array + how many times I have clicked shuffle into my code.我在“相互缠绕”数组时遇到问题 + 我点击了多少次随机播放到我的代码中。 Honestly, I am getting confused, with so many 'help blogs' who all have different ways of doing things and I'd truly TRULY appreciate any help to get me sorted.老实说,我很困惑,有这么多“帮助博客”,他们都有不同的做事方式,我真的非常感谢任何帮助让我分类的帮助。

This is my current code to produce the list of fruits and being able to display it on my page.这是我当前的代码,用于生成水果列表并能够在我的页面上显示它。

 function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const r = Math.floor(Math.random() * (i + 1)); [arr[i], arr[r]] = [arr[r], arr[i]]; } return arr; }; const array = ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"]; function printArray(arr) { return arr.reduce((acc, n, i) => { return acc.concat(i < arr.length - 1? `${n}\n `: `${n}`); }, ''); }; function shuffle() { const copiedArr = array.map(n => n); const shuffledArray = shuffleArray(copiedArr); document.getElementById("array").innerText = printArray(shuffledArray); } function restore() { document.getElementById("array").innerText = printArray(array); } restore();
 <div class="container"> <span id="array"><pre></pre></span> </div> <br> <br> <button onclick="shuffle()" value="randomize">Shuffle!</button> <button onclick="restore()">Retore</button>

To be honest I have tried so many different things I am lost and confused.老实说,我尝试了很多不同的东西,我感到迷茫和困惑。 And so am hoping to start from scratch this is my code and I am trying to get a counter to keep track of every time I click shuffle that resets when Reset is clicked.因此,我希望从头开始,这是我的代码,我正在尝试获取一个计数器来跟踪每次我单击随机播放时都会在单击“重置”时重置。

The closure in JavaScript can be solution but it's a bit challenging to understand. JavaScript 中的闭包可以解决,但理解起来有点困难。

const add = (function () {
  let counter = 0;
  return function () {counter += 1; 
  return counter}
})();
// Call add() 3 times
add();
add();
add(); 
// the counter is now 3

The variable add is assigned to the return value of a self-invoking function.变量add被赋值给一个自调用的返回值function。

The self-invoking function only runs once.自调用 function 只运行一次。 It sets the counter to zero (0), and returns a function expression.它将计数器设置为零 (0),并返回 function 表达式。

This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.这样add就变成了function。“妙”的地方在于它可以访问父scope中的计数器。

This is called a JavaScript closure.这称为 JavaScript 闭包。 It makes it possible for a function to have "private" variables.它使得 function 可以拥有“私有”变量。

The counter is protected by the scope of the anonymous function, and can only be changed using the add function.该计数器受匿名 function 的 scope 保护,只能使用 add function 进行更改。

Here you go. While swahili geeks answer is correct.给你go。虽然斯瓦希里语极客的回答是正确的。 It is quite confusing for a learner.这对学习者来说是相当混乱的。

So I took a different approach.所以我采取了不同的方法。 You define a state object for your application and work upon it.您为您的应用程序定义一个 state object 并对其进行处理。

It would be nice to wrap the whole thing in a function to isolate the scope of declared functions and variables and not pollute the window, but you get there on your speed.最好将整个东西包装在 function 中以隔离声明的函数和变量的 scope 并且不会污染 window,但你可以按自己的速度到达那里。

Also note how I am using a spread operator [...arr] to clone an array.另请注意我是如何使用扩展运算符[...arr]来克隆数组的。 No need to .map(n => n)不需要.map(n => n)

 const state = { originalArray: ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"], currentArray: ["Apple", "Pear", "Apricot", "Nashy", "Kiwi", "Watermelon"], numberOfShuffles: 0, }; const outputElement = document.getElementById("js-array"); const counterElement = document.getElementById("js-count"); function formatArray(arr) { return arr.reduce((acc, n, i) => { return acc.concat(i < arr.length - 1? `${n}\n`: `${n}`); }, ""); } function shuffleArray(arr) { for (let i = arr.length - 1; i > 0; i--) { const r = Math.floor(Math.random() * (i + 1)); [arr[i], arr[r]] = [arr[r], arr[i]]; } return arr; } function shuffle() { const copiedArr = [...state.currentArray]; const shuffledArr = shuffleArray(copiedArr); state.currentArray = shuffledArr; state.numberOfShuffles++; updateUi(); } function restore() { state.currentArray = [...state.originalArray]; state.numberOfShuffles = 0; updateUi(); } function updateUi() { outputElement.innerText = formatArray(state.currentArray); counterElement.innerText = state.numberOfShuffles; } updateUi();
 <pre id="js-array"></pre> <br /> <span id="js-count"></span> <br /> <br /> <button onclick="shuffle()">Shuffle!</button> <button onclick="restore()">Restore</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM