gpt4 book ai didi

javascript - 在 JavaScript 中调用/触发匿名函数的正确方法?

转载 作者:行者123 更新时间:2023-12-02 15:06:55 24 4
gpt4 key购买 nike

假设我有这个函数,它就像 Array.push 的不同版本,并利用 pump_array ,其中包含一些不同的逻辑:

var array_values = [];

function pump_array(needle, haystack, callback) {
var pushed = false;

if(haystack.indexOf(needle) === -1) {
haystack.push(needle);
pushed = true;
}

if(typeof callback == 'function') {
callback(haystack, pushed);
}
}

现在如果我以这种方式使用它:

var pump_array_callback = function(new_data_in_array_values, pushed) {
if(pushed) {
console.log('added "first" into "array_values[]"');
} else {
console.log('"first" already in "array_values[]"');
}

console.log(new_data_in_array_values);
};

pump_array('first', array_values, pump_array_callback);
pump_array('first', array_values, pump_array_callback);

ojit_code 的第一个函数调用将输出:

added "first" into "array_values[]"

第二个会做相反的事情:

"first" already in "array_values[]"

基本上,我的问题是:

这是在函数中或其他地方调用/执行匿名函数的正确方法吗:

if(typeof callback == 'function') {
callback(haystack, pushed);
}

还有其他方法可以以更务实的方式做同样的事情吗?

最佳答案

您对回调的调用没问题。

And are there any other methods of doing the same, in a more pragmatic way?

对于此用例,您根本不应该使用回调。只要可以就使用返回值(并且您几乎不需要回调)。

function pump_array(needle, haystack) {
if (haystack.indexOf(needle) === -1) {
haystack.push(needle);
return true;
}
return false;
}

var array_values = [];
function pump_array_result(pushed) {
if (pushed) {
console.log('added "first" into "array_values[]"');
} else {
console.log('"first" already in "array_values[]"');
}
console.log(array_values);
};

pump_array_result(pump_array('first', array_values));
pump_array_result(pump_array('first', array_values));

关于javascript - 在 JavaScript 中调用/触发匿名函数的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com