在不转换原始数组的情况下迭代多维数组



所以我看了多个来源,包括寻找JavaScript数组值和https://codereview.stackexchange.com/questions/52119/calculate-all-possible-combinations-of-an-array-of-arrays-or-strings的所有组合,我仍然提出了一个空白。

我将字符串"35 w 35 ave"分割成" "上的数组,然后将其与值数组进行比较。下面是对象:

var addressObject = {
    ave : ["av", "aven", "avenu", "avenue", "avn", "avnue"],
    w : ["west", "wst", "w"]
};

我将其添加到var address = txtNode.val().split(' ');中返回数组['35','w','35','ave']然后我将该数组放入嵌套的forEach循环中,如下所示:

address.forEach( function(addressElement, indexOfAddressElement) {
    var abbreviationMatch = addressObject.hasOwnProperty(addressElement);
    if (abbreviationMatch) { 
        function addSentenceVariationsToAddressLists(arrayToLookAt) {
            arrayToLookAt.forEach(function (anItem, a) {
                var y = address.splice(indexOfAddressElement, 1, anItem); 
                addressLists.push(address.join(" ")); 
            })
        }
        var elementsFromArray = addressObject[addressElement];
        addSentenceVariationsToAddressLists(elementsFromArray);
    }    
});
console.log(addressLists);

返回["35 west 35 ave", "35 wst 35 ave", "35 w 35 ave", "35 w 35 av", "35 w 35 aven", "35 w 35 avenu", "35 w 35 avenue", "35 w 35 avn", "35 w 35 avnue"]

我的问题是:我如何返回"ave""wst""west"的所有变化,而不仅仅是"w",包括address数组的原始值?

好吧,所以这花了一些时间来弄清楚,因为我试图调整你的代码,而不是完全重构。不幸的是,我认为这段代码在底层结构方面存在缺陷,因此我最终不得不对其进行了相当大的修改,以使其按照预期的方式工作,并具有最佳的重用能力。

请记住,此代码不考虑其他街道变化(街道,地点,驱动器等)或其他方向(东,北,南)。它也没有考虑到双重街道名称。例如,"25w west ave"将用变体代替"west",而不是w。如果/当你添加其他街道/方向变体时,这将是一个问题,因为那里有像"123 west avenue street"或"123 north west avenue"等街道。

让我知道这是如何为你工作的,如果你有任何问题!

var addressObject = {
  streets: ["av", "aven", "avenu", "avenue", "avn", "avnue", "ave"],
  directions: ["west", "wst", "w"]
};
var adr = "35 w 35 ave";
function addSentenceVariationsToAddressLists(address, indexes) {
  var addresses = [];
  addressObject.streets.forEach(function(street) {
    addressObject.directions.forEach(function(direction) {
      var y = address.slice();
      y[indexes.streetIndex] = street;
      y[indexes.directionIndex] = direction;
      addresses.push(y.join(" "));
    });
  });
  return addresses;
}
function getAddressLists(address) {
  address = address.split(" "); // ['35', 'w', '35', 'ave']
  var indexes = {
    streetIndex: -1,
    directionIndex: -1
  };
  address.forEach(function(addressElement, indexOfAddressElement) {
    if (addressObject.streets.indexOf(addressElement) > -1) {
      indexes.streetIndex = indexOfAddressElement;
    } else if (addressObject.directions.indexOf(addressElement) > -1) {
      indexes.directionIndex = indexOfAddressElement;
    }
  });
  return addSentenceVariationsToAddressLists(address, indexes);
}
var addressLists = getAddressLists(adr);
console.log(addressLists);

相关内容

  • 没有找到相关文章

最新更新