how to parse array and create new array with parsed values?
I have an array
var data = new Array("1111_3", "1231_54", "1143_76", "1758_12");
now I want to parse data[0] to get 1111.
var ids = new Array();
// example: ids = Array("1111", "1231", "1143", "1758");
and copy all ids from data to ids Array.
is it possible to do it 开发者_运维百科like in php or do i need to use loops?
Thanks.
Really simple:
var ids = [];
for(var i = 0, j = data.length; i < j; ++i) {
var idString = data[i];
ids.push(idString.substring(0, idString.indexOf('_')));
}
elegance:
data.map(function(x){
return x.split('_')[0];
})
This IS part of the ECMA-262 standard.
But, if you care about supporting old outdated sub-par browsers, use jQuery (or whatever other framework you are using; almost all of them define a custom map
function):
$.map(data, function(x){
return x.split('_')[0];
})
What you want to do is called a 'map.' Some browsers support them, but if you want to be safe you can use underscore.js (http://documentcloud.github.com/underscore/)
You'd end up with either:
_(data).map(function(x){
return x.split('_')[0];
});
or
_.map(data, function(x){
return x.split('_')[0];
});
If you have a really big array it may be faster to join it to a string and split the string, rather than using any of the iterative methods to form it one by one.
var data = ["1111_3", "1231_54", "1143_76", "1758_12"];
var ids= data.join(' ').replace(/_\d+/g,'').split(' ');
alert(ids)
/* returned value: (Array)
1111,1231,1143,1758
*/
精彩评论