![](/img/trans.png)
[英]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 called countDots(x) that takes a string as an argument and returns the number of dots (.) it contains
我最近開始學習編碼,並試圖學習如何創建函數,但是我發現它相當困難。
如何編寫一個名為countDots(x)的函數,該函數將字符串作為參數並返回其包含的點數(。)。例如x =“ www.google.com”,該函數將返回2。
我會這樣:
function dotCounter(x) { return x.split('.').length -1; } document.write( dotCounter("www.google.com") );
請嘗試這個
function countDots(x){
return((x.match(/\./g) || []).length)
}
正如您所說的,您現在正在學習編碼,您不需要速度優化的代碼。 我建議這樣做-它只使用幾乎所有編程語言中都出現的想法:
function countDots(str) {
var count = 0;
for (var x = 0; x < str.length; x++) {
if str.charAt(x) == '.' {
count++;
}
}
return count;
}
一旦對基礎有所滿意,就可以擔心速度了! 祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.