回调访问数据

时间:2013-11-22 06:36:25

标签: javascript jquery

我创建了一个小函数,它检查我提交给它的标签列表,并将好的标签放在一个好的数组中,坏的放在坏的数组中。

这一切都在回调中完成,所以一旦完成,我的其余代码就可以继续了。

我对如何从回调中访问原始函数中的数据感到困惑。

function findTags() {
    validateTags(tags, function () {
        //How do I access the bad array here?
        console.log('These tags are bad ' + badArray.join(','))
    });
}

//This will validate the tags submitted and strip out anything bad from them.
//We will return either success if everything is good or an array of the bad tags to fix.

function validateTags(tags, callback) {
    var badArray = new Array(),
        goodArray = new Array();
    tags = tags.split(',');
    for (var i = 0; i < tags.length; i++) {
        //If the tag contains just alphanumeric, add it to the final array.
        if (tags[i].match(/^[a-z0-9\s]+$/i)) {
            goodArray.push(tags[i]);
        } else {
            //Since we didnt match an alphanumeric, add it to the bad array.
            badArray.push(tags[i]);
        }
    }
    //console.log(badArray);
    //console.log(goodArray);
    if (callback) {
        callback(badArray);
    }
}

1 个答案:

答案 0 :(得分:2)

简单。只需在回调定义中使用参数 -

validateTags(tags, function (badArray) {
    //How do I access the bad array here?
    console.log('These tags are bad ' + badArray.join(','))
});

在验证标记定义中,您将badArray作为参数传递给callback来电。因此,只需为回调定义定义一个参数,它就会将数组作为其值捕获。