如果定义了值,为什么会得到一个未定义的值?使用 eval()

Why do I get an undefined value if the value is defined? using eval()

本文关键字:未定义 一个 定义 eval 使用 为什么 如果      更新时间:2023-09-26

我不太明白为什么我的控制台会出现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'");

提前感谢伙计们!

你得到undefined的原因是因为你的变量m(你认为它包含字符串"state")有一个尾随空格。在方括号表示法中使用以读取对象的属性时,这将返回undefined .

这是使用良好的老式调试发现的: https://jsfiddle.net/wLs3o9mk/- 您对console.dir的使用掩盖了问题,它似乎折叠了多个空格(如 HTML)。当更改为没有console.log时,它变得非常明显。