更改在函数中添加到哪个变量

时间:2019-03-01 16:45:40

标签: javascript arrays function variables

我正在努力了解如何更改在函数中添加到哪个变量。

基本上,当用户选择旅馆时,需要将其添加到hotelSelection中。当他们单击“下一步”时,它会更新包含餐馆的地图,而当他们选择餐馆时,则需要进入restaurantSelection。这就是我要坚持的一点,将其从酒店选择更改为餐厅选择。

这是一个片段:

var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";

function chooseSelection(resultIndex) {

    var locationName = document.getElementById('locationName-' + resultIndex);

    hotelSelection = `<div class="input-group" id="Hotel-chosen">
                                <li class="list-group-item"> 
                      <strong>${locationName.innerHTML}</strong><br>`;

    var locationRating = document.getElementById('locationRating-' + 
    resultIndex);

    hotelSelection += `rating: ${locationRating.innerHTML}</li>`

    console.log("Hotel Selection: " + hotelSelection);

}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

这是函数如何通信的核心。您正在做的是在较高的“闭包”中访问变量。这有其优点和缺点,而您现在发现的缺点之一是它不是非常灵活。

如果您可以使用函数的返回值来代替这种方式,则可以灵活地执行您要说的话。例如:

var hotelSelection = "";
var restaurantSelections = "";
var sightSelections = "";

function chooseSelection(resultIndex) {

    var locationName = document.getElementById('locationName-' + resultIndex);

    var selection = `<div class="input-group" id="Hotel-chosen">
                                <li class="list-group-item"> 
                      <strong>${locationName.innerHTML}</strong><br>`;

    var locationRating = document.getElementById('locationRating-' + 
    resultIndex);

    selection += `rating: ${locationRating.innerHTML}</li>`

    console.log("Hotel Selection: " + hotelSelection);
    return selection;
}

如果这样做,则在调用函数时,只需将返回值分配给变量,如下所示:

hotelSelection = chooseSelection(someIndex);
sightSelections = chooseSelection(someIndex);