javascript - arrays with the same names in different functions -


i have 2 arrays named same thing in 2 separate functions. assumed arrays local each function, of values first function messing values in other function. when change name of array in second function works. seems go against scope if ask me. why doesn't first solution work?

problem: have function lettercounti(str) take str parameter being passed , return first word greatest number of repeated letters. example: "today, greatest day ever!" should return greatest because has 2 e's (and 2 t's) , comes before ever has 2 e's. if there no words repeating letters return -1. words separated spaces.

non working solution:

function repeatcount(word) {     tmp = [];     (var = 0;i<word.length;i++) {         tmp.push(word.filter(function(value) {return value === word[i]}).length)     }     return math.max.apply(math,tmp); }  function lettercounti(str) {     tmp = [];     str = str.split(/[^a-za-z]/).filter(function(value) {return value != "";});     (var = 0;i<str.length;i++) {         tmp.push(repeatcount(str[i].split("")));     }     console.log(tmp);     return str[tmp.indexof(math.max.apply(math,tmp))]; } console.log(lettercounti("today, greatest day ever!")); 

non working solution output:

array [ 2, 1, 2, 1 ]  "today"  

working solution:

function repeatcount(word) {     tmp = [];     (var = 0;i<word.length;i++) {         tmp.push(word.filter(function(value) {return value === word[i]}).length)     }     return math.max.apply(math,tmp); }  function lettercounti(str) {     count = [];     str = str.split(/[^a-za-z]/).filter(function(value) {return value != "";});     (var = 0;i<str.length;i++) {         count.push(repeatcount(str[i].split("")));     }     console.log(count);     return str[count.indexof(math.max.apply(math,count))]; } console.log(lettercounti("today, greatest day ever!")); 

working solution output:

array [ 1, 1, 1, 2, 1, 2 ] "greatest" 

the problem because tmp arrays not defined var keyword within functions. defining variables without var keyword makes them global scope, hence 1 affecting other.

to solve this, declare variables var keyword, local function scope expect them be.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -