我想在记录数组搜索后更新变量和数组项,并想知道在Javascript中执行它的最佳方法是什么。
在这种情况下,如果在变量和区域项之间找到匹配项,则应将邮政编码项附加到变量。
对于数组项也需要做同样的事情,但我认为for循环在这种情况下最有效,因为需要以某种方式访问每个单独的项。
顺便说一句,由于我的程序性质,总会有匹配。 此外,我需要能够区分singleAddress和multipleAddresses变量。
希望这段代码能更好地解释一下:
// before search
var singleAddress = "Mount Farm";
var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
// this is the record which the search needs to be run against
plot = [{
postcode: "MK1",
area: "Denbigh, Mount Farm",
}, {
postcode: "MK2",
area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
}, {
postcode: "MK3",
area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
}, {
postcode: "MK4",
area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
}, {
postcode: "MK5",
area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
}]
// after search is run then:
// var singleAddress = "Mount Farm, MK1"
// var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
答案 0 :(得分:1)
好的,您无法轻松更改原始数据格式。实际记录有多大,多久更新一次?因为如果它不是很大并且每秒没有多次改变并且您要进行多次查找,那么创建我提到的映射然后再读取会更有效率从它,而不是每次都通过原始结构。我将在这个答案中假设这样。希望它有所帮助。
此代码中的另一个假设是:每个区域只有一个邮政编码。
function convertPlot(plot)
{
var mapping={}
plot.forEach(function (r){
var locations=r.area.split(/,\s*/)
for(var i=0, loc; loc=locations[i]; i++)
mapping[loc]=r.postcode
})
return mapping
}
当你得到情节时,只需这样做:
mapping=convertPlot(plot)
然后查找功能变得微不足道了:
function lookup(adr)
{
if('string' == typeof adr)
return adr+", "+mapping[adr]
if(('object' == typeof adr) && adr instanceof Array)
return adr.map(lookup)
throw new TypeError("cannot look up something that isn't a string or array or strings")
}