我想知道这之间的区别:和JavaScript的迭代VS过滤图
function doesCodeExist(arrvalidcodes, code) {
var hit = arrvalidcodes.filter(function(item){
return (code === item)
}).map(function(item){
return true;
});
if (hit[0] === true) {
return true;
} else {
return false;
}
}
这样的:
function doesCodeExist(arrvalidcodes, code) {
for (var i = 0; i < arrvalidcodes.lenght; i++) {
if (arrvalidcodes[i] === code) {
return true;
}
}
return false;
}
两个代码应该做同样的事情,简单地返回true
如果代码是在提供的阵列或以其他方式返回false
。
哪一个被认为是最可读的,哪个是更有效的方法呢?
我会说第二个块效率更高,因为只要你找到了一些东西,就存在for循环,而第一个循环遍历所有的项目(并且它也不会读取,我确定它更喜欢第二部分 – Icepickle
你认为哪个更具可读性?这个'if(hit [0] === true){ return true; } else { return false; }'可以缩短为:'return hit [0] === true;' – Craicerjack
@Craicerjack'hit [0]'不能是除'true'或'undefined'之外的任何东西(只有在'hit.length === 0'时后一种情况) 。无论哪种方式,像这样使用'.filter'和'.map'是一个_horrendous_非直观和低效的方法来检查数组中是否存在元素。 – Alnitak