考虑以下数组:javascript数组排序?
var things = ['sandwich', 17, '[email protected]', 3, 'horse', 'octothorpe', '[email protected]', '[email protected]'];
排序阵列分为三个他人号码之一,字符串之一,并且有效的电子邮件地址之一。丢弃无效的地址。
考虑以下数组:javascript数组排序?
var things = ['sandwich', 17, '[email protected]', 3, 'horse', 'octothorpe', '[email protected]', '[email protected]'];
排序阵列分为三个他人号码之一,字符串之一,并且有效的电子邮件地址之一。丢弃无效的地址。
var emails = [], strings = [], numbers = [];
things.forEach(function (e) {
if (typeof e == "string") {
if (e.indexOf("@") != -1) { // "looks" like an email if it contains @
if (isEmail(e)) emails.push(e); // push if it is a valid email
}
else strings.push(e);
}
else if (typeof e == "number") {
numbers.push(e);
}
});
function isEmail(str) { return /** true if str is a valid email **/ }
我会离开它给你拿出一个正确的isEmail
功能。
你需要的是使用Array对象的过滤函数。
例子:
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
你需要写3个自定义过滤功能为每个需要的阵列。
前两个条件是微不足道的,对于第三个条件,我建议选择一个正则表达式来满足您的验证邮件的要求。一个短的将是^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}$
。
问候, 阿林
+1很好的答案。让OP在没有给予他的情况下继续下去。 – 2010-10-04 21:45:53
(function(arr) {
var a = [], b = [], c = [];
for (var i = 0; i < arr.length; i += 1) {
if (typeof arr[i] === "number") {
a.push(arr[i]);
} else if (isValidEmail(arr[i])) {
b.push(arr[i]);
} else if (typeof arr[i] === "string") {
c.push(arr[i]);
}
}
return [a, b, c];
}());
isValidEmail(s)返回true,如果该参数是表示有效电子邮件的字符串。你是最好的使用这个正则表达式的...
顺便说一句,你用这样的方式,分配上述表达式给一个变量,然后将此变量包含三个数组作为其项目...
您将a,b,c分配给同一个数组。您需要为每个数组指定一个新的实例,否则您将推送到内存中的同一个数组。 – 2010-10-04 21:49:32
更正。谢谢你指出。 – 2010-10-04 21:51:43
做你自己的作业... – 2010-10-04 21:35:57
做结果数组必须自己排序..? – 2010-10-04 21:39:16
@Josh,或者至少*标记*作为家庭作业......另外,我们应该如何从两个数组中得到三个数字? – 2010-10-04 21:41:07