在JavaScript中将函数作为参数传递

时间:2018-08-21 08:26:43

标签: javascript java parameters porting

必须将一小段代码从JavaScript移植到JAVA:

var N = 3;
var w = 8, h = 8;

var matrix = [ 

               [1, 0, 0, 0, 0, 0, 0, 0],
               [1, 1, 0, 0, 0, 0, 0, 0],
               [1, 1, 1, 0, 0, 0, 0, 0],
               [1, 1, 1, 1, 0, 0, 0, 0],
               [1, 1, 1, 1, 1, 0, 0, 0],
               [1, 1, 1, 1, 1, 1, 0, 0],
               [1, 1, 1, 1, 1, 1, 1, 0],
               [1, 1, 1, 1, 1, 1, 1, 1]

             ];

//[1, 1, 1, 1, 1, 1, 0, 1, 1]
console.log(complexFunction(2, 1));

//first function
function simpleFunction(f_) {

    var out = new Array(N * N);

    for (var y = 0; y < N; y++) {
        for (var x = 0; x < N; x++) {

        out[x + y * N] = f_(x, y);

        }
    }

    return out;

};

//second function     
function complexFunction(x_, y_) {

    return simpleFunction(function (dx, dy) { return matrix[(x + dx) % w][(y + dy) % h]; });

};

尝试了Callable,但没有成功。 理想情况下,移植结果应与JavaScript源具有相同的结构。

1 个答案:

答案 0 :(得分:-1)

不幸的是,我必须使用没有lambda的Java 7, 因此必须使一切尽可能简单:

var httpBaseProtocolFilter = new HttpBaseProtocolFilter();
    httpBaseProtocolFilter.MaxVersion = HttpVersion.Http20;
    HttpClient httpClient = new HttpClient(httpBaseProtocolFilter);
    var requestUrl = Global.ServerUrl;

    httpClient = SetHeaders(httpClient);

    httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
    HttpResponseMessage response = null;

    if (requestMehtod == ApplicationConstants.RequestType.POST) //Request type POST
    {
        if (postData != null && postData.Count > 0)
        {
            Dictionary<string, string> pairs = new Dictionary<string, string>();
            foreach (var item in postData)
            {
                val = (String.IsNullOrWhiteSpace(item.Value)) ? "" : item.Value;
                pairs.Add(item.Key, val);
            }

            Uri uri = new Uri(requestUrl);
            HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
            response = await httpClient.PostAsync(uri, formContent).AsTask(cts.Token);
        }
    }

    responseText = await response.Content.ReadAsStringAsync();