[英]What's the best way to filter an array to create another array?
我想基于字符串过滤数组中的项目并将它们保存到新数组,然后在第二个数组上执行其他一些函数。 我怎样才能做到最好?
这是我到目前为止所拥有的。
for (var i = 0; i < array.length; i++) {
var num = i;
var item = array.entries[i];
var str = item.content;
var newArray = new Array();
if (str.indexOf("filter") !== -1) {
// If the content of the item contains a given string then ad it to the array.
newArray.push(item);
if (num === array.length) {
// When we reach the end of the first array, perform something on the new array.
doSomeFunction();
}
}
function doSomeFunction() {
// Now do something with the new array
for (var j = 0; j < newArray.length; j++) {
// Blah, blah, blah...
}
}
}
谢谢你的帮助。
ECMAScript 5支持数组上的filter
方法。
例如:
> [1,2,3,4].filter(function(v) { return v % 2 == 0})
[ 2, 4 ]
您可以参考MDN的文档来查看用法。
但请注意,某些浏览器不支持此功能,出于兼容性问题,您可以考虑使用es5-shim或下划线 。
在你的情况下,对字符串数组的工作。 您可以将filter
与map
一起使用
例如,要过滤以'index'开头的所有字符串,然后从中获取尾随数字。
var ss = [
"index1",
"index2",
"index3",
"foo4",
"bar5",
"index6"
];
var nums = ss.filter(function(s) {
return /^index/.test(s);
}).map(function(s) {
return parseInt(s.match(/(\d+)$/)[1], 10);
});
console.log(nums);
上面的脚本给你[1,2,3,6]
像这样的东西:
function arrayFromArray(a,f){
var b=[];
for (var x=0;x<a.length;x++) {
if (f(a[x])) {
b.push(a[x]);
}
}
return b;
}
function predicateIsEven(i){
return i%2==0;
}
var arr=[1,2,3,4,5,6];
var evens=arrayFromArray(arr,predicateIsEven);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.