我无法弄清楚为什么我在我的控制台中获得undefined
...
迭代的每个对象都定义了属性。
我哪里出错?
该集合如下所示:
var a = [
{
city: 'Tucson',
state: 'AR',
zipcode: 85701
},
{
city: 'Orlando',
state: 'FL',
zipcode: 32828
},
{
city: 'Apopka',
state: 'FL',
zipcode: "32703",
},
{
city: 'Compton',
state: 'CA',
zipcode: 90220
}
];
这是功能:
function reduce(collection, condition){
var map = [];
for (let v in collection){
var cl = [], r, e, matches, m;
if ('string' === typeof condition) {
r = new RegExp(/([\w]+)\s*?(?=(>|<|>=|<=|==|===|!=|!==))/g);
matches = condition.match( r );
var nm = condition;
matches.forEach(function(m, index){
// outputs state console.log(m);
nm = nm.replace(m, (collection[v][String(m)]) + ' ' );
console.dir(collection[v]);
console.dir(m + " replaced by " + collection[v][m] + ", gets you: " + nm);
});
cl.push(m);
//if (eval(condition) === true) { map.push(collection[v]); }
} else if ('object' === typeof condition){
for (let c in condition){
r = new RegExp("(" + collection[v][c] + ")*(>|<|>=|<=|==|===|!=|!==)", "g");
e = condition[c];
matches = condition[c].match( r );
if (0 < matches.length) {
matches.forEach(function(m, index){
if ( condition[c].indexOf(c) === -1 ) {
e = e.replace(m, ( (typeof collection[v][c] === 'string') ? "'" + collection[v][c] + "'" : collection[v][c] ) + " " + m);
}
});
};
cl.push(e);
}
if (eval(cl.join(" && ")) === true) { map.push(collection[v]); }
};
console.log(cl.join(" && "));
}
return map;
}
...
以下是对:
的呼吁 var floridians = reduce(a, "state == 'FL'");
先谢谢你们!
答案 0 :(得分:0)
获得undefined
的原因是因为您的变量m
(您认为其中包含字符串“state”)具有尾随空格。当使用方括号表示法来读取对象的属性时,将返回undefined
。
使用良好的'老式调试https://jsfiddle.net/wLs3o9mk/发现了这一点 - 您使用console.dir
掩盖了问题,它似乎会折叠多个空格(如HTML)。当更改为console.log
时,它变得非常明显。