簡體   English   中英

檢測變量是否在不同的函數中已更改

[英]Detect whether a variable has been changed within a different function

我是javascript和谷歌地圖的新手。 我有一個輸入,在提交時,對值進行地理編碼,我希望它:

  • 如果存在地圖(某些東西已經輸入並且已經成功地進行了地理編碼),則重新定位它
  • 否則以該點為中心創建地圖。

我的代碼有點像這樣:

var map;

function getlatlong() { //this function gets the input value and then geocodes
    if(map.length){recentermap()} //if map exists, recenter map
    else{createmap()} //create map
}

function createmap(){ //this function creates the map (by editing `var map`)
    var map = new google.maps.Map();
}

我想我只是不明白js變量是如何工作的......我的問題是,如果我在第二個函數中更改它,如何看看var map是否已被更改?

當你說:

function createmap(){ //this function creates the map (by editing `var map`)
    var map = new google.maps.Map();
}

您正在創建一個名為map的局部變量,該變量僅存在於createmap函數中。 您希望使用在外部作用域中聲明的map變量,因此不應使用var關鍵字:

function createmap(){ //this function creates the map (by editing `var map`)
    map = new google.maps.Map();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM