Editing object's value in Javascript

87 Views Asked by At

I need to edit an value in the object. Add a new word(value) to the object's value. But add this new word if only it is'n already there.

e.g.:

var obj = {className: 'open menu'}

new word (value) - 'new', result -> obj.className='open menu new'

new word (value) - 'open ', result -> obj.className='open menu' (the same)

THis is my code:

function addClass(object, value){   
  var str = object.className;  //taking a string from object value
  var arr = str.split(' ');  // converting it to massive

  if (arr.indexOf(value) !== undefined) { //proceed if value exist 
       str = str + " " + value     // making new sring   
       object.className = str 

     {
  return object.className
}

var obj = {
  className: 'open menu'
}

console.log(addClass(obj, 'new')); // obj.className='open menu new' 
console.log(addClass(obj, 'open'));  // No change    , but I get 'open menu open' !

What is wrong? Help, please.

2

There are 2 best solutions below

1
On
  if (arr.indexOf(value) !== undefined) { //proceed if value exist 

indexOf will never return undefined. If it's not found, it returns -1. Use that, and it should be fine:

  if (arr.indexOf(value) !== -1) { //proceed if value exist 
2
On

There is a syntax error in your example above. The if statement is not properly closed. I suspect it was just a typo since it seems you were running it in your application and getting results.

Aside from this, you were so close. You actually want to run the code in the if statement when the word does not exist. Array.prototype.indexOf() returns -1 if a value is not found, it does not return undefined.

function addClass(object, value){   
  var str = object.className;  //taking a string from object value
  var arr = str.split(' ');  // converting it to massive

  if (arr.indexOf(value) === -1) { //proceed if value DOES NOT exist 
    str = str + " " + value;     // making new sring   
    object.className = str; 
  }
  return object.className;
}

var obj = {
  className: 'open menu'
}

console.log(addClass(obj, 'new')); // obj.className='open menu new' 
console.log(addClass(obj, 'open'));  // No change    , but I get 'open menu open' !