2012-02-09 2 views
0

안녕하세요 배열이 있습니다 : enter image description here 이 배열이 커질 수 있다고 생각하면 region [], city [] 및 area []를 추출하는 가장 좋은 방법은 무엇입니까? region5, city5, area5, region6 , city6, area6? 자바 스크립트 배열에서 3 개의 배열을 만듭니다

+0

문자열 배열이 아닌 개체 배열을 사용하십시오. – zzzzBov

+0

정확히 무슨 뜻인지 확실치 않습니다. 모든 cityX 요소를 city [] 배열에, 모든 "areaX"요소를 "area []"영역 등에 추출하고 싶습니까? – MeLight

+0

이미지가 아닌 코드를 입력하십시오. – Jivings

답변

0

나는 같은 것을 할 것입니다 :

function getData(array){ 

    var cities = [], regions = [], areas = [], 
     item, i, j, value, 
     hash = array.slice(5, array.length); //we don't need the first 6 values. 
           //assuming the data always comes in this order. 

    hash.sort();//to get values in the right order 
    for(i= 0, j = hash.length; i<j; i++){ 

     item = hash[i]; 
     value = item.split("=")[1]; 

     if(item.indexOf("a"=== 0)){ 
      areas.push(value); 
     } 
     else if(item.indexOf("c"=== 0)){ 
      cities.push(value); 
     }else if(item.indexOf("r"=== 0)){ 
      regions.push(value); 
     } 

    } 

    return { 
     areas : areas, 
     cities : cities, 
     regions : regions 
    }; 
} 
0

여기에 내가 이것을하는 방법입니다 감사합니다

var strings = ["city1=Bellevue", "city2=Seattle", "area1=Sound", "area2=Boston"]; 
var keys = {}; 

for(var i = 0; i < strings.length; i++) 
{ 
    var parse = /^([a-z]+)[0-9]+\=([a-z]+)$/i 
    var result = parse.exec(strings[i]); 
    var key = result[1]; 
    var value = result[2]; 
    if(!keys[key]) keys[key] = []; 
    keys[key].push(value); 
} 

alert(keys['city']); 
alert(keys['area']); 

이것은 (I 각 키의 끝에있는 숫자를 무시) 문제가되지 않는 키의 순서를 가정합니다. 물론 해당 숫자를 구문 분석하여 배열 색인으로 사용할 수있는 코드를 수정할 수도 있습니다. 적어도이 일이 시작되기를 바랍니다.

0
var info = ["cities1=Bellevue", "cities2=Seattle", "areas1=Sound", "areas2=Boston", "regions1=Region1", "regions2=Region2"]; 


    var cities = []; 
    var areas = []; 
    var regions = []; 

    for(var i = 0; i < info.length; i++){ 
     var item = info[i]; 
     if(/cities\d+/.test(item)){ 
      cities.push(item.split("=")[1]); 
     } 
     else if(/areas\d+/.test(item)){ 
      areas.push(item.split("=")[1]); 
     } 
     else if(/regions\d+/.test(item)){ 
      regions.push(item.split("=")[1]); 
     } 
    } 

의 예처럼 항상있을 것입니다 배열을 가정. 그렇지 않으면 항목이 분리 된 상태 점검을 추가하십시오.

관련 문제