[英]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.