Вопрос

I am converting the following code from Python to JS.

lat *= (math.pi / 180.0)
lon *= (math.pi / 180.0)

n = lambda x: wgs84_a / math.sqrt(1 - wgs84_e2*(math.sin(x)**2))

x = (n(lat) + alt)*math.cos(lat)*math.cos(lon)
y = (n(lat) + alt)*math.cos(lat)*math.sin(lon)
z = (n(lat) * (1-wgs84_e2) +alt)*math.sin(lat)

Most of this is no issue at all but I don't get how to convert the n= line with the lambda function into JS.

Это было полезно?

Решение

JavaScript functions are first-class objects you can create dynamically, so lambdas are just a feature of how the language works.

Here's a rough translation:

var n = function(x) {
    return wgs84_a / Math.sqrt(1 - wgs84_e2*Math.pow(Math.sin(x), 2));
};

Just as with Python's lambda, that expression will create the function and assign it to n, but not call it. The code later will call it via n. It's also a "closure" because it will use the variables you've referenced inside it when it's called (it has an enduring reference to the variables and uses their values as of when it's called, not when it's created).

Features:

  • Declare n using var.

  • Start a function expression with function.

  • Arguments to that function are given names within the () after function.

  • Use the return keyword to return a value from the function.

  • Use JavaScript's various Math functions, including Math.pow rather than ** (JavaScript doesn't have an operator for that).

A function expression like the one above creates the function when the code is reached in the step-by-step execution (just like any other expression). Another alternative is to use a function declaration instead:

function n(x) {
    return wgs84_a / Math.sqrt(1 - wgs84_e2*Math.pow(Math.sin(x), 2));
}

This creates the function when execution enters the scope containing it; it happens before any step-by-step code in that scope is executed. (People sometimes call this "hoisting" because regardless of where it appears, it's like the declaration was moved -- "hoisted" -- to the top of the scope.) It still uses the variables it closes over as of when it's called, not when it's created; it's just another way to create the function.

Другие советы

var n = function (x) { return wgs84_a / Math.sqrt(1 - wgs84_e2 * Math.pow(Math.sin(x), 2)) }

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top