I'm tring to create new function like below
function NVConvertToFV (array, func) {
var funcA = [];
for(var i=0; i<array.length; i++) {
var valueF = function (callback) {
func(array[i], callback);
}
funcA[i] = valueF;
}
return funcA;
}
But, 'func(array[i], callback);' recognized as just a string.
ex.
var funcA = [];
var msg = ['hello ', 'it ', 'is ', 'impossible!'];
function alert (para, callback) {
console.log(para);
callback(null);
}
funcA = NVConvertToFV(msg, alert);
console.log(String(funcA));
results:
function (callback) {func(array[i], callback);},
function (callback) {func(array[i], callback);},
function (callback) {func(array[i], callback);},
function (callback) {func(array[i], callback);},
Is there any possible way 'func' and 'array[i]' recognized as function and array? like,
function (callback) {alert('hello', callback);},
function (callback) {alert('it', callback);},
function (callback) {alert('is', callback);},
function (callback) {alert('impossible', callback);},
if someone help me that would be really gladful.
In NVConvertToFV()
use array.forEach()
instead of a normal for-loop in order to correctly capture the current value in the array so that the inner inline callback holds the correct reference. For example:
function NVConvertToFV(array, func) {
var funcA = new Array(array.length);
array.forEach(function(val, i) {
funcA[i] = function(callback) {
func(val, callback);
};
});
return funcA;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.