Remove var from a function

0

I have the following function. The problem I have is that I can not get the var c of the function contains . Then the console.log(c) that I have in my if does not work. How can I change contains to make this work?

function contains(target, pattern) {
  var value = 0;
  pattern.forEach(function(word) {
    value = value + target.includes(word);
  });
  var c = value;
  return (value === 1)
}

if (contains(a, b)) {
  console.log(a);
  console.log(c);
} else {
  //false statement..do nothing
}
    
asked by CalvT 20.03.2017 в 13:47
source

4 answers

1
var a, c;
function contains(target, pattern) {
  var value = 0;
  pattern.forEach(function(word) {
    value = value + target.includes(word);
  });
  c = value;
  return (value === 1)
}

if (contains(a, b)) {
  console.log(a);
  console.log(c);
} else {
  //false statement..do nothing
}
    
answered by 20.03.2017 / 13:55
source
1

Removing the variable from the function:

var c = -1; //Aquí la declaras

function contains(target, pattern) {
  var value = 0;
  pattern.forEach(function(word) {
    value = value + target.includes(word);
  });
  c = value;
  return (value === 1)
}

if (contains(a, b)) {
  console.log(a);
  console.log(c);
} else {
  //false statement..do nothing
}
    
answered by 20.03.2017 в 13:55
1

You could simply return value and verify that:

  • If it is equal to one ( 1 ) it means "contains it".
  • If it is different from one, "it does not contain it".

Example:

function contains(target, pattern) {
  var value = 0;
  pattern.forEach(function(word) {
    value = value + target.includes(word);
  });
  return value;
}

var a = ['a'];
var b = ['a', 'b', 'c'];
var c = contains(a, b);

if (c === 1) {
  console.log(a);
  console.log(c);
} else {
  //false statement..do nothing
}
    
answered by 20.03.2017 в 13:56
1

You have several alternatives to be able to use the variable c . Some of them are these:

Declare the variable c out of the context of the function, in a more global scope :

var c;

function contains(target, pattern) {
  var value = 0;
  pattern.forEach(function(word) {
    value = value + target.includes(word);
  });
  c = value;
  return (value === 1)
}

if (contains(a, b)) {
  console.log(a);
  console.log(c);
} else {
  //false statement..do nothing
}

Return an object with the two values needed:

function contains(target, pattern) {
  var value = 0;
  pattern.forEach(function(word) {
    value = value + target.includes(word);
  });

  return { c: value, contains: (value == 1) };
}

var result = contains(a, b); 
if (result.contains) {
  console.log(a);
  console.log(result.c);
} else {
  //false statement..do nothing
}

Finally, simply implement it with callbacks .

    
answered by 20.03.2017 в 14:02