为什么如果JavaScript array.split('').push('something')返回数字,而不返回数组? [英] Why if JavaScript array.split(' ').push('something') returns number, but not array?

查看:102
本文介绍了为什么如果JavaScript array.split('').push('something')返回数字,而不返回数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 obj.className = obj.className.split('').push(cls)-在obj.className中写数字,而不是数组?

Why obj.className = obj.className.split(' ').push(cls) - writes number in obj.className, but not array?

我有代码:

var obj = {
                className: "math lol"
          }

function addClass(obj, cls){
    if(!(cls in obj.className.split(' ')))
        obj.className = obj.className.split(' ').push(cls);
}

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

为什么 alert(obj.className)显示 3 ,并且不显示数组 ['math','lol','PH']

Why alert(obj.className) display 3, and don't display array ['math', 'lol', 'PH']?

推荐答案

Push返回集合中的项目数,而不是集合本身。

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

尝试:

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

而不是:
obj.className = obj。 className.split('').push(cls);

这篇关于为什么如果JavaScript array.split('').push('something')返回数字,而不返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆