鍍金池/ 問答/HTML/ JavaScript數(shù)組處理

JavaScript數(shù)組處理

var nodeLists = ["/data1/chenleileitest/1T/"]

如何快速將上述數(shù)組變換成如下的格式

["/data1/","/data1/chenleileitest/","/data1/chenleileitest/1T/"]

我想的是使用split對(duì)數(shù)組元素劃分,然后再拼接,但這是對(duì)數(shù)組元素只有一個(gè)的情況比較好處理,如果數(shù)組的元素比較多的情況呢?

["/data1/chenleileitest/1T/","/boot/gurb2/themes/system/","/sys/dev/block/8:16/device/"]

將其轉(zhuǎn)換成如下形式

["/data1/","/data1/chenleileitest/","/data1/chenleileitest/1T/","/boot/","/boot/gurb2/","/boot/gurb2/themes/","/boot/gurb2/themes/system/","/sys/","/sys/dev/","/sys/dev/block/","/sys/dev/block/8:16/","/sys/dev/block/8:16/device/",]
var nodeList  = [];
nodeList = nodeLists.map(function(value, index, array) {
            return '/'+value
          }).filter(function(item,index, array){
            return item !== '/'
          })

得到的結(jié)果是:

["/data1", "/chenleileitest", "/1T"]

實(shí)現(xiàn)想要的結(jié)果需要,第一的加上第二個(gè),第一個(gè)加第二個(gè)加第三個(gè),組成最終想要的結(jié)果

回答
編輯回答
心癌

建議不要使用數(shù)組來儲(chǔ)存數(shù)據(jù),其實(shí)我猜想你的本意是想要一個(gè)dom類的數(shù)據(jù)類型,那何不用對(duì)象來操作呢,直接對(duì)每個(gè)字符串進(jìn)行操作,轉(zhuǎn)成一個(gè)類似dom的數(shù)組,方法思路也現(xiàn)成,就是dom解析。

2017年3月2日 05:15
編輯回答
尋仙

思路很簡(jiǎn)單,對(duì)數(shù)組中的某一項(xiàng),都先進(jìn)行拆分,然后每拼接一個(gè)路徑,就存儲(chǔ)一次,直到路徑拼接完成

var arr = ["/data1/chenleileitest/1T/","/boot/gurb2/themes/system/","/sys/dev/block/8:16/device/"];

function ss(arrs){
    let result = [];

    // 數(shù)組中的每個(gè)路徑
    arrs.map((item)=>{
        let s = '/',
            res = [];

        item.split('/').map((_)=>{
            if(_){
                // 拼接路徑,并把每次拼接完成的路徑存儲(chǔ)到res中
                s += _+'/';
                res.push(s);
            }
        });

        // 把數(shù)組中每個(gè)拼接的路徑都存儲(chǔ)到總數(shù)組中
        result = result.concat(res);
    });
    return result;
}
ss(arr);
2017年6月26日 12:48
編輯回答
疚幼

用單個(gè)元素的方法在外面再循環(huán)一次不就行了嗎

2018年4月3日 05:10
編輯回答
雨萌萌

跟前面的思路基本一致,ES3/ES5版本

var data = ["/data1/chenleileitest/1T/", "/boot/gurb2/themes/system/", "/sys/dev/block/8:16/device/"];

var result = [];

for(var i=0,len=data.length;i<len;i++){
    var item = data[i].split('/').slice(1, this.length - 1);
    for(var j=0,len02=item.length;j<len02;j++){
        result.push('/'+item.slice(0, j+1).join('/')+'/');
    }
}
    
console.log(result)
2017年2月14日 15:25
編輯回答
維他命
    var nodeLists = ['/Atest1/Atest2/Atest3/','/Btest1/Btest3/','/Ctest1/Ctest2/Ctest3/Ctest4/'];

    function strToArr(str){
        var arr = [];
        if(str[0] === '/' && str[str.length-1] === '/'){
            for(var i = 1; i < str.length; i++){
                if(str[i] === '/'){
                    arr.push(str.slice(0,i+1));
                }
            }
        }
        return arr;
    }
    console.log(strToArr(nodeLists[0]));

    function nodeSplit(arr){
        var resultArr = [];
        arr.forEach(function(item){
            resultArr = resultArr.concat(strToArr(item));
        });
        return resultArr;
    }

    console.log(nodeSplit(nodeLists));
2018年4月19日 01:35