迭代多维数组而不转换原始数组

时间:2016-09-27 22:34:05

标签: javascript object multidimensional-array

所以我查看了多个来源,包括Finding All Combinations of JavaScript array valueshttps://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"的所有变体,包括{{1}的原始值数组?

1 个答案:

答案 0 :(得分:0)

好的,所以这花了一些时间来弄清楚,因为我试图调整你的代码而不是完全重构。不幸的是,我认为这个代码在底层结构方面存在缺陷,因此我最终需要进行相当多的改动才能使其按照预期的方式运行并具有最佳的重用功能。

请注意,此代码不会考虑其他街道变化(街道,地点,驾车等)或其他方向(东,北,南)。它也没有考虑双街道名称。例如,“25 w west ave”将用变化代替“west”,而不是w。如果/当你添加其他街道/方向变化时,这将是一个问题,因为那里有街道,如“123西大道街”或“123西北大道”等。

让我知道这对您有何帮助,如果您有任何问题!

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);