jon*_*ony 1 javascript return function
我需要将变量传递给另一个函数,但它不会返回任何东西.注意:它不会向外部返回任何内容,但如果我在函数内部执行document.write,它可以完美地工作..
<script type="text/javascript">
//funtion1
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(Location);
}
function Location(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
return (latitude,longitude);
}
//function2
function initialize() {
document.write(latitude);
document.write(longitude);}
</script>
Run Code Online (Sandbox Code Playgroud)
你误解了一些概念.
首先,return (a, b)将评估为return b.几乎不需要逗号运算符.如果要返回数组,请使用return [a, b].
其次,getCurrentPosition是异步的.Location如果找到了位置,它将执行.所以在你打电话的时候document.write,还没有取得这个位置.
最后,您根本没有使用返回值.如果要使用函数的返回值,请使用eg var result = func(...).但是,在这种情况下,这没有意义.
我并不完全知道你在追求什么,但任何依赖于这个位置的东西都应该放在回调中(Location在这种情况下).只有在调用回调时才能使用poision.在这个回调中返回一些东西是没有意义的,因为返回值不用于getCurrentPosition.
编辑:看看你的代码,你需要这样的东西,而不是return:
function Location(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
useValuesForSomethingElse(latitude, longitude); // call other function with position data
}
Run Code Online (Sandbox Code Playgroud)