gpt4 book ai didi

javascript - 使用回调创建函数

转载 作者:行者123 更新时间:2023-12-03 08:50:11 26 4
gpt4 key购买 nike

我试图通过解决这个问题来理解回调函数如何正常工作:

Complete the following merge function such that is behaves as described in the example below. Merge should take two arrays of numbers of identical length and a callback function.

var merge = function(array1, array2, callback){  
//your code here.
}

var x = merge([1, 2, 3, 4], [5, 6, 7, 8], function(a, b){
return a + b;
});

//x should now equal [6, 8, 10, 12].

Now, use your merge function to complete the euclid function defined below. Euclid should take two arrays, each of which has an equal number of numerical elements, and return the euclidean distance between them. For a quick refresher on what Euclidean distance is, check here

var euclid = function(coords1, coords2){  
//Your code here.
//You should not use any loops and should
//instead use your original merge function.
}

var x = euclid([1.2, 3.67], [2.0, 4.4]);

//x should now equal approximately 1.08.

我可以在没有回调的情况下完成此操作,但最终我想知道如何使用回调作为参数来完成这样的函数。

最佳答案

给你..

var merge = function(array1, array2, callback) {
var result = [];
if (array1.length === array2.length) {
while (array1.length > 0) {
result.push(callback.call(null, array1.shift(), array2.shift()));
}
}
return result;
}

var euclid = function(coords1, coords2) {
var x = merge(coords1, coords2, function(a, b) {
return a - b;
})
return Math.sqrt(Math.pow(x[0], 2) + Math.pow(x[1], 2));
}

console.log(euclid([1.2, 3.67], [2.0, 4.4]));

关于javascript - 使用回调创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708375/

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