简体   繁体   English

如何编写一个称为countDots(x)的函数,该函数将字符串作为参数并返回包含的点数(。)。

[英]How do I write a function called countDots(x) that takes a string as an argument and returns the number of dots (.) it contains

I have recently started learning coding and am trying to learn how to create functions but I am finding it quite difficult. 我最近开始学习编码,并试图学习如何创建函数,但是我发现它相当困难。

How would write a function called countDots(x) that takes a string as an argument and returns the number of dots (.) it contains.Eg x = "www.google.com" the function will return with 2. 如何编写一个名为countDots(x)的函数,该函数将字符串作为参数并返回其包含的点数(。)。例如x =“ www.google.com”,该函数将返回2。

I would do it this way: 我会这样:

 function dotCounter(x) { return x.split('.').length -1; } document.write( dotCounter("www.google.com") ); 

Please try this 请尝试这个

function countDots(x){
    return((x.match(/\./g) || []).length)
}

As you say you're learning to code at the moment, you don't need speed-optimised code. 正如您所说的,您现在正在学习编码,您不需要速度优化的代码。 I'd suggest this - it only use ideas that turn up in almost all programming languages: 我建议这样做-它只使用几乎所有编程语言中都出现的想法:

function countDots(str) {
  var count = 0;
  for (var x = 0; x < str.length; x++) {
    if str.charAt(x) == '.' {
      count++;
    }
  }
  return count;
}

You can worry about speed once you're happy that you've got the basics! 一旦对基础有所满意,就可以担心速度了! Good luck 祝好运

暂无
暂无

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

相关问题 如何编写从服务器端 JavaScript 调用的 Java 方法,该方法将 JS 回调函数作为参数? - How do I write a Java method, to be called from server side JavaScript, that takes a JS callback function as an argument? 如何编写一个将电话号码作为字符串接收并验证它是否是美国电话号码的函数? - How do I write a function that takes in a telephone number as a string and validates if it is a US phone number or not? 如何编写一个接受值数组并返回对象的函数 - How do I write a function that takes an array of values and returns an object 我该如何编写称为validate(z)的函数,该函数将字符串作为参数,如果包含1个“ @”符号和至少1个“。”,则返回true;否则返回false - How can i write function called validate(z) which takes a string as argument & return true if contain 1 “@” symbol & at least 1 “.” & false otherwise 如何获取参数字符串并返回包含的点(。)上的数字? - how do you take a string of arguments and return the number on dots (.) it contains? 我想写一个 JS function ,它接受一个数字并返回一个以千 k 和百万 m 作为后缀的缩写字符串 - I want to write a JS function which takes a number and returns an abbreviated string for thousands k and millions m as suffix 如何将函数编写为事件处理程序和带参数的可调用函数? - How do I write a function as both an event handler and a callable function that takes an argument? Function 以数字作为参数并返回 boolean javascript - Function that takes a number as an argument and returns a boolean javascript 我如何编写一个接受 10 个字母的字符串并在 Javascript 中返回相应电话号码字符串的 function? - How do i write a function that accepts a 10-character string of letters and returns a corresponding phone number string in Javascript? 如何编写一个接收作为字符串的语义版本号输入的函数 - How to write a function that takes in a semantic version number input that is a String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM