I have an array in javascript:

a=["jhgkhjgk3j_jhgkjhgk","8797823_0120120", "aaaaa_bbb"]

I want to get

b=["jhgkhjgk3j","8797823", "aaaaa"]

and

c=["jhgkjhgk","0120120", "bbb"].

because of "_" delimiter.

Are there any way to get that done without using for loop statement?

有帮助吗?

解决方案

Just for fun, here's an ECMAScript 6 solution.

let [b, c] = a.reduce(function(res, s, i) {
    [res[0][i], res[1][i]] = s.split("_");
    return res;
}, [[],[]]);

Will work in Firefox today, and in other browsers in the hopefully not too distant future.

其他提示

var a= ["jhgkhjgk3j_jhgkjhgk","8797823_0120120", "aaaaa_bbb"],
    b = [],
    c = [];

a.forEach(function (value, key) {
    a[key] = value.split('_');
    b.push(a[key][0]);
    c.push(a[key][1]);
});

Here is a version that should work in Chrome. It also uses reduce:

var result = a.reduce(function(result, current, i) {
    var parts = current.split(/_/);
    result[0].push(parts[0]);
    result[1].push(parts[1]);

    return result;
}, [[], []]);

var b = result[0];
var c = result[1];

Something like this ES5:

 var a=["jhgkhjgk3j_jhgkjhgk","8797823_0120120", "aaaaa_bbb"];

    var items = a.reduce(function(a,b){
        a[0].push(b.split('_')[0]);
        a[1].push(b.split('_')[1]);
        return a;
    },[[],[]]);

    console.log(items);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top