Write a JavaScript function that accepts two arguments, a string and a letter and the function will count the number of occurrences of the specified letter within the string. Sample arguments: 'w3resource.com', 'o' Expected output: 2 ...
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); // countOccurrences([1,1,2,1,2,3], 1) -> 3 当前URL 使用window.location.href来获取当前URL。 const currentUrl = _ => window.location.href; // currentUrl() -> 'https:...
while (regex.test(str)) count++; return count; } countOccurrences(/x/g, '_x_x'); // 2 // 问题一: 如果不加/g标识,会进入无限循环 countOccurrences(/x/, '_x_x'); // 无限循环 // 问题二: lastIndex未设置为0 var regex = /x/g; regex.lastIndex = 2; countOccurrences(regex, '_...
11. `countOccurrences`:检测数值出现次数const countOccurrences =(arr, val)=>arr.reduce((a, v)=>(v === val ? a +1: a),0); countOccurrences([1,1,2,1,2,3],1);//3 12. `deepFlatten`:递归扁平化数组constdeepFlatten =arr=>[].concat(...arr.map(v=>(Array.isArray(v) ? deepF...
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 12. `deepFlatten`:递归扁平化数组 const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5] ...
functioncountOccurrences(str,target){returnstr.split(target).length-1;} 16. 随机生成指定范围内的整数 有时,你可能需要生成指定范围内的整数,而不仅仅是整数。getRandomInt函数可以接受min和max两个参数,然后生成一个在这两个值之间的随机整数。 functiongetRandomInt(min,max){if(min>max){[min,max]=[max...
console.log(countOccurrences([ 1, 3, 3, 4, 3, 3, 2, 3], 3)); // 5 9. capitalizeWord 此代码片段将给定字符串中每个单词的首字母转为大写。 const capitalizeWord = (string) => string.replace(/\b[a-z]/g, (char) => char.toUpperCase()); ...
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 12. deepFlatten:递归扁平化数组 const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten...
countOccurrences([2,4,6,2,5,2], 2) // 3 countOccurrences([1,4,6,2,5,6], 6) // 2 7、字谜 此片段代码用于检查特定字符串是否为字谜。字谜是可以改写成另一个词的词。 const Anagram = (string1, string2) => { const normalize = str =>str ...
constcountOccurrences =(arr, val) =>arr.reduce((a, v) =>(v === val ? a +1: a),0);countOccurrences([2,4,6,2,5,2],2)// 3countOccurrences([1,4,6,2,5,6],6)// 2 7、字谜 此片段代码用于检查特定字符...