Skip to content Skip to sidebar Skip to footer

Why If Javascript Array.split(' ').push('something') Returns Number, But Not Array?

Why obj.className = obj.className.split(' ').push(cls) - writes number in obj.className, but not array? I have code: var obj = { className: 'math lol' }

Solution 1:

Push returns the number of items in the collection, not the collection itself.

Try:

var currentItems = obj.className.split(' '); currentItems.push(cls); obj.className = currentItems

Instead of: obj.className = obj.className.split(' ').push(cls);

Solution 2:

JavaScript 'push()' method returns the length of the new array. That's why when you assign obj.className it's value becomes 3. In order to fix it, do this:

var obj = {
                className: "math lol"
          }

functionaddClass(obj, cls){
    alert(obj.className.split(' '));
    if(!(cls in obj.className.split(' '))) {
        obj.className = obj.className.split(' '); //first splitting (NOT ASSIGNING THE LENGTH)
        obj.className.push(cls);  //then pushing
    }
}

addClass(obj, 'PH');
alert(obj.className);

DEMO

Solution 3:

Try:

obj.className = obj.className.split(' ');
obj.className.push(cls);

Instead of:

obj.className = obj.className.split(' ').push(cls);

.push() returns the number of elements and affects the object.

In the future, try splitting your code into smaller pieces while troubleshooting, as such:

console.log(obj);
console.log(obj.className)
console.log(obj.className.split(' '));
console.log(obj.className.split(' ').push(cls));

Which clearly shows where the problem was in that cascade.

Solution 4:

Along with not assigning the result of an array push to get back the array (which, as others have pointed out, returns the number of values in the array after the push), you also don't want to use in to determine whether the value you want to check is already in the array. You typically use in to check for the existence of a property on an object, but if you're going to use it with an array, then you would use it to check if a value is at a given index:

var list = ['AB', 'BC', 'CD'];
if (2in list) {
  // if there is a value at index 2 of list, then this evaluates
}

Instead, you can use indexOf on the string that you already have:

if (obj.className.indexOf(cls) === -1) {
  obj.className += ' ' + cls;
}

You can also use indexOf to check for a value in an array, but your support matrix is modern browsers (no IE8 unless you polyfill it.) By using in to check, your conditional will always evaluate to true (because you're negating something that will always be false) and you will always add the class regardless of whether it was already present.

Solution 5:

in javascript arrays you have to use

console.log(obj.className);

print an array

Post a Comment for "Why If Javascript Array.split(' ').push('something') Returns Number, But Not Array?"