热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何计算项目在数组中的次数-Howtocountnumberoftimesanitemisinanarray

IvedecidedtojusttryagainfromthestartsinceImabitmoreawakenowandgooverbuildingth

I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be many ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.

我决定从一开始就再试一次,因为我现在更加清醒,然后逐步重建。我已经看了一些答案,似乎有很多方法可以解决这个问题。我正试图用我迄今学到的东西来做这件事。我已经了解了变量,基本函数,对象,数组,'this'和push方法。我知道,虽然,for while,for循环,虽然for循环是我理解最好的。

Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...

这是我建立这个的新方法,我知道这是不必要的长,但我希望能够基本了解如何以非常简单的方式拼凑我学到的不同的东西。这更多的是学习如何构建简单的程序。然后我将继续微调程序,使其更简洁,更聪明。如果你能看看并告诉我如何继续我到目前为止所做的事情......

Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.

这是代码,理想情况下,当有一个新的“访问者”询问他们的姓名和号码时,我想运行一个函数。然后使用给定的名称和编号创建一个新的“客户”对象,并将其推送到“访问者”数组。一旦我成功地解决了这个问题,我会使用循环检查数组,如果访问者是新的,并在每次访问时更新他们的访问次数。

//array that will contain 'Customer' objects
var visitors = [john];

//Customer object
function Customer(name, phonenumber){
  this.name = name;
  this.phOnenumber= phonenumber;
//will eventually add a "visits" method logging number of visits

}

var john = new Customer("john smith", "333");

//visitor funtion that runs everytime there is a new visitor
var visitor = function(){

  //visitor does not have a set name or number yet
  var userNumber = "variable userNumber is currently equal to " + 0;
  var userName = "variable userName is currently set to " + undefined;
  console.log(userName, userNumber);

  //ask for visitor name and number
  var askNumber = prompt("type your number");
  var askName = prompt("what is your name?");

  //store user name and number in two variables
  var userNumber = "variable 'userNumber' is now equal to " + askNumber; 
  var userName = "variable userName is now set to " + askName;

  //print out the new variables 
  console.log(userNumber);
  console.log(userName);

  //print who the phone number belongs to, this lets me see that the above code worked correctly
  var userNumber = askNumber;
  var userName = askName;
  console.log("Phone number " + userNumber + " belongs to " + userName);

  //make new customer object with the given name and number
  var userNumber = new Customer();
  userNumber.name = askName;
  userNumber.phOnenumber= askNumber;

  console.log("properties of " + userNumber);  

};

the last bit returns "properties of [object, object]" why?

最后一位返回“[object,object]的属性”为什么?

8 个解决方案

#1


Not only did you confuse yourself, but you crashed the browser! :-)

你不仅迷惑自己,而且还使浏览器崩溃了! :-)

(The for loop never terminates because you push a new value to the list on every iteration.)

(for循环永远不会终止,因为在每次迭代时都会将新值推送到列表中。)

I could tell you what's wrong with the code in more detail, but you'll learn a lot more if you chase it down yourself. So what you need now is to learn the art of debugging.

我可以更详细地告诉你代码有什么问题,但如果你自己追逐它,你会学到很多东西。所以你现在需要的是学习调试的艺术。

Add a debugger statement at the beginning of your test() function:

在test()函数的开头添加一个调试器语句:

var list = ["111", "222", "333", "444", "555", "666"];

var test = function(input){
    debugger;
    var info = prompt("hi " + input + " what is your name?");
    for(i=0; i

Now run test() and it will stop in the debugger at that statement. Look at the different panels in the debugger - you can view your variables and other stuff. Find the place where it has controls to let you step through your code. Single-step through the code and look at the variables as you go. You will soon discover what the problems are. In most browsers there are also keyboard shortcuts to let you step through the code more easily.

现在运行test(),它将在该语句的调试器中停止。查看调试器中的不同面板 - 您可以查看变量和其他内容。找到它有控件的位置,让您单步执行代码。单步执行代码并随时查看变量。您很快就会发现问题所在。在大多数浏览器中,还有键盘快捷键,可让您更轻松地单步执行代码。

If you use Chrome, here is an introduction to the Chrome DevTools. There are similar tutorials for the other browsers too.

如果您使用Chrome,则以下是Chrome DevTools简介。其他浏览器也有类似的教程。

#2


heres an algorithm :

下面是一个算法:

Use an object to store the user no. and the count. like :

使用对象存储用户号。和伯爵。喜欢 :

{"222":"3","444":"1"}

this means 222 has visited 3 times and 444 visited once. now every time a user checks in:

这意味着222次访问过3次,444次访问过一次。现在每次用户签入时:

  1. see if the key with the user's number exists, if yes increment the count. if no, add a new entry with count = 1.
  2. 查看是否存在具有用户编号的密钥,如果是则增加计数。如果不是,请添加count = 1的新条目。

  3. check if the number is 5, if yes get free coffee and reset count to zero. skip if no.
  4. 检查数字是否为5,如果是,则获取免费咖啡并重置计数为零。如果没有,请跳过

#3


I would solve the problem by storing the visit count in a dictionary that maps each customer's ID to the number of times they have visited. The dictionary is initially empty. When you look up an ID in the dictionary for the first time, you'll get undefined, which tells you that you must initialize the value.

我会通过将访问计数存储在一个字典中来解决问题,该字典将每个客户的ID映射到他们访问过的次数。字典最初是空的。当您第一次在字典中查找ID时,您将获得未定义,这告诉您必须初始化该值。

The following demonstration has a couple of buttons that you can use to make Alice or Bob visit the shop. Click on the blue button at the bottom to start the demo.

以下演示有几个按钮,您可以使用这些按钮让Alice或Bob访问该商店。单击底部的蓝色按钮开始演示。

function message(s) {  // Simple output for a code snippet.
  document.getElementById('display').innerHTML += s + '
'; } var coffeeCount = {}; // Stores the number of visits by each customer. function customerVisit(id) { // Called when a customer visits. if (coffeeCount[id] === undefined) { // Check for first visit. coffeeCount[id] = 0; // Initialize the visit count. } var count = ++coffeeCount[id]; // Increment the visit count. message(id+': '+count+' visit'+(count == 1 ? '' : 's')); if (count % 5 == 0) { // Check for free coffee. message('→ Free coffee for customer '+id+'!'); } }




#4


Try including utilization of input elements; set visits count as value of property id, info at object list; call test with value of input element : id ; or at prompt : info . At five visits , display coffee , reset value of id to 0.

尝试包括输入元素的使用;将访问次数设置为属性id的值,对象列表中的信息;使用input元素的值调用test:id;或者在提示时:info。在五次访问时,显示咖啡,将id的值重置为0。

var list = {
  "111": 0,
  "222": 0,
  "333": 0,
  "444": 0,
  "555": 0,
  "666": 0
};

var test = function test(id) {
  coffee.innerHTML = "";
  var info;
  if (id.length > 0 && !/^(\s)/.test(id)) {
    if (list.hasOwnProperty(id)) {
      ++list[id];

    } else {
      list[id] = 1;
    }
    info = confirm("hi " + id + " this is your " + list[id] + " visit");
  } else {
    info = prompt("hi, please enter an id");
    if (!!info && !/^(\s)/.test(info) && list.hasOwnProperty(info)) {
      list[info] = 1;
      confirm("hi " + info + " this is your " + list[info] + " visit");
    } else {
      info = prompt("hi, please input a different id");
      if (!!info && !/^(\s)/.test(info) && !list.hasOwnProperty(info)) {
        list[info] = 1;
        confirm("hi " + info + " this is your " + list[info] + " visit");
      }
    };
    alert("please try a different id")
  };

  for (var id in list) {
    if (list[id] === 5) {
      alert("hi " + id + ", thanks for visting " + list[id] + " times");
      coffee.innerText = "☕";
      list[id] = 0;
      break;
    }
  };

  console.log(list);

};

var inputs = document.querySelectorAll("input");
var coffee = document.getElementById("coffee");
coffee.style.fOntSize= "5em";

inputs[1].Onclick= function(e) {
  test(inputs[0].value)
};


#5


n is number of costumer

n是客户的数量

Initially array is [0,0,0,.....n times]

最初的数组是[0,0,0,..... n次]

All values are 0 because no costumer has visited the shop.

所有值均为0,因为没有客户访问过该商店。

For n=5 array would look like

对于n = 5阵列看起来像

var a=[0,0,0,0,0];

1)To solve this problem in array.

1)在阵列中解决这个问题。

2)Suppose we have array of size n.

2)假设我们有大小为n的数组。

3)then index of the array will be 0...n-1

3)然后数组的索引将是0 ... n-1

4)So we can map id of costumer to the index.

4)因此我们可以将客户的id映射到索引。

5)And value will keep count of the number of visit for the index.

5)并且值将保留索引的访问次数。

6)a[5]=11; here 5 is index and 11 is value

6)[5] = 11;这里5是索引,11是值

7)For our problem if customer with id i we increment a[i]=a[i]+1 if he visits .

7)对于我们的问题,如果客户有身份我,如果他访问,我们增加[i] = a [i] +1。

8) Then we can check

8)然后我们可以检查

if(a[i]+1 === 5) {
   console.log("Custumer "+ i + " get a free coffee");
   a[i]=0;
}
else {
   a[i]=a[i]+1;
}

#6


I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be manyt ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.

我决定从一开始就再试一次,因为我现在更加清醒,然后逐步重建。我已经看了一些答案,似乎有很多方法可以解决这个问题。我正试图用我迄今学到的东西来做这件事。我已经了解了变量,基本函数,对象,数组,'this'和push方法。我知道,虽然,for while,for循环,虽然for循环是我理解最好的。

Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...

这是我建立这个的新方法,我知道这是不必要的长,但我希望能够基本了解如何以非常简单的方式拼凑我学到的不同的东西。这更多的是学习如何构建简单的程序。然后我将继续微调程序,使其更简洁,更聪明。如果你能看看并告诉我如何继续我到目前为止所做的事情......

Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.

这是代码,理想情况下,当有一个新的“访问者”询问他们的姓名和号码时,我想运行一个函数。然后使用给定的名称和编号创建一个新的“客户”对象,并将其推送到“访问者”数组。一旦我成功地解决了这个问题,我会使用循环检查数组,如果访问者是新的,并在每次访问时更新他们的访问次数。

//array that will contain 'Customer' objects
var visitors = [john];

//Customer object
function Customer(name, phonenumber){
  this.name = name;
  this.phOnenumber= phonenumber;
//will eventually add a "visits" method logging number of visits

}

var john = new Customer("john smith", "333");

//visitor funtion that runs everytime there is a new visitor
var visitor = function(){

  //visitor does not have a set name or number yet
  var userNumber = "variable userNumber is currently equal to " + 0;
  var userName = "variable userName is currently set to " + undefined;
  console.log(userName, userNumber);

  //ask for visitor name and number
  var askNumber = prompt("type your number");
  var askName = prompt("what is your name?");

  //store user name and number in two variables
  var userNumber = "variable 'userNumber' is now equal to " + askNumber; 
  var userName = "variable userName is now set to " + askName;

  //print out the new variables 
  console.log(userNumber);
  console.log(userName);

  //print who the phone number belongs to, this lets me see that the above code worked correctly
  var userNumber = askNumber;
  var userName = askName;
  console.log("Phone number " + userNumber + " belongs to " + userName);

  //make new customer object with the given name and number
  var userNumber = new Customer();
  userNumber.name = askName;
  userNumber.phOnenumber= askNumber;

  console.log("properties of " + userNumber);  

};

the last bit returns "properties of [object, object]" why?

最后一位返回“[object,object]的属性”为什么?

#7


I will give you a short function to check how many times a specific value is at the array:

我将给你一个简短的函数来检查特定值在数组中的次数:

function countHowManyTimesAValueIsOnArray(arr, valueToCheck){
    return  arr.filter(function(arrayValueToCompare){
        return arrayValueToCompare === valueToCheck;
    }).length
}

Attention for the use of '===' instead of '=='. This will compare the value considering its type. 222 will not be found as "222"

注意使用'==='而不是'=='。这将比较考虑其类型的值。 222将不会被发现为“222”

#8


No need to complicate things here's an simple way, just add a count function that search how many times user has enter

这里不需要复杂的事情是一个简单的方法,只需添加一个计数函数来搜索用户输入的次数

 var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
  var info = prompt("hi " + input + " what is your name?");
  var check=0;
    for(i=0; i

推荐阅读
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了如何使用PHP向系统日历中添加事件的方法,通过使用PHP技术可以实现自动添加事件的功能,从而实现全局通知系统和迅速记录工具的自动化。同时还提到了系统exchange自带的日历具有同步感的特点,以及使用web技术实现自动添加事件的优势。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • LeetCode笔记:剑指Offer 41. 数据流中的中位数(Java、堆、优先队列、知识点)
    本文介绍了LeetCode剑指Offer 41题的解题思路和代码实现,主要涉及了Java中的优先队列和堆排序的知识点。优先队列是Queue接口的实现,可以对其中的元素进行排序,采用小顶堆的方式进行排序。本文还介绍了Java中queue的offer、poll、add、remove、element、peek等方法的区别和用法。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
author-avatar
chunhuai
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有