javascript - 将“A,B,C”这种字符串转换为数组,为什么"".split(',').length=1
怪我咯
怪我咯 2017-04-11 13:03:04
[JavaScript讨论组]

var A="1,2,3";
A.split(',')=[1,2,3];
A.split(',').length=3;
var B="";
A.split(',')=[""];
A.split(',').length=1;
如何使空字符串转化为长度为0的数组

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(3)
PHP中文网
return A.length == 0 ? [] : A.split(",");
高洛峰
 public String[] split(CharSequence input, int limit) {
        int index = 0;
        boolean matchLimited = limit > 0;
        ArrayList<String> matchList = new ArrayList<String>();
        Matcher m = matcher(input);
 
        // Add segments before each match found
        while(m.find()) {
            if (!matchLimited || matchList.size() < limit - 1) {
                String match = input.subSequence(index, m.start()).toString();
                matchList.add(match);
                index = m.end();
            } else if (matchList.size() == limit - 1) { // last one
                String match = input.subSequence(index,
                                                 input.length()).toString();
                matchList.add(match);
                index = m.end();
            }
        }
 
        // If no match was found, return this
        if (index == 0)
            return new String[] {input.toString()};

split方法的源码。因为正则匹配不到字符。。。就直接返回一个数组 ,数组中包着 空字符串 所以他的长度是1
其实你可以对A进行判断是否是空字符串,空字符串就直接赋值空数组

ringa_lee

判断字符串是否为空,为空则返回空数组,如果不为空则返回数组

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号