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.
indexOf
will never returnundefined
. If it's not found, it returns-1
. Use that, and it should be fine: