2016-07-29 6 views
-1

からの配列をしているの作成:Javascriptが私は、コードは以下の文字列

var selector="a,b,c/m,n", 
property = "width,height/font-size"; 

は私がグループ化する新しい配列に(スラッシュで区切られた)文字列の各セットを。

ので、私は(基本的に)これで終わるだろう:

var selector_array1 = [a,b,c]; 
var selector_array2 = [m,n]; 
---- 

var property_array1 = [width,height]; 
var property_array2 = [font-size]; 
.... 

ので、私は、forループ2で終わるだろう(と思う)、のような:

for(outer loop){//for each selector array 
    for(inner loop){//for each item in selector array apply each property in property array 

    } 
} 

ベア心​​の中でそれができます(そう何の前進を分割するためにスラッシュがない)のような1つの値/プロパティだけを持っている:

var selector="a/m", 
property = "width/font-size"; 

またはこのような:

var selector="a", 
property = "width"; 
+0

?配列 '[" a "]'と空の配列 '[]'?これでも '.split()'を使うことができます。 – nnnnnn

+0

結果配列に文字列または変数を含める必要がありますか? 'var selector_array1 = [a、b、c];'の 'a、b、c'とは何ですか? – alexmac

+0

'var selector =" a、b、c/m、n "、arr = selector.split("/")map(e => e.split("、 ")); console.log(arr); ' – Redu

答えて

3

スラッシュのないものでもsplitを使用できます。一度スラッシュに分割し、その結果をコンマで区切ります。あなたは文字列のプロトタイプのsplitメソッドを使用する必要があることを行うには

function extractData(input) { 
 
    // Separate by /'s 
 
    return input.split('/') 
 
    .map(function(str) { 
 
     // For each of the new strings, split them on commas 
 
     return str.split(','); 
 
    }); 
 
} 
 

 
var data = extractData('a,b,c/width,height'); 
 
console.log(data[0].toString(), '|', data[1].toString()); 
 

 
data = extractData('a,b,c'); 
 
console.log(data[0].toString()); 
 

 
data = extractData('a/width,height'); 
 
console.log(data[0].toString(), '|', data[1].toString()); 
 

 
data = extractData('a/width'); 
 
console.log(data[0].toString(), '|', data[1].toString());

0

var selector="a,b,c/m,n", 
 
property = "width,height/font-size"; 
 

 
function splitString(s){ 
 
    // Split the string with the character/
 
    // And loop through the array 
 
    return s.split('/').map(function(stringWithComa){ 
 
    // Return the result of the string split 
 
    return stringWithComa.split(',') 
 
    }) 
 
} 
 

 
console.log(splitString(selector)); 
 
console.log(splitString(property));

はそれがお役に立てば幸いです。)お気軽にお問い合わせいけません質問;)

0

split()と配列を使用する方法があります。 `セレクター= ""`から出力されるもの

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title></title> 
 
</head> 
 
<body> 
 

 
<script type="text/javascript"> 
 
var selector="a,b,c/m,n"; 
 
var property = "width,height/font-size"; 
 

 
var selector_array1 = new Array(); 
 
var selector_array2 = new Array(); 
 

 
var property_array1; 
 
var property_array2; 
 

 
var selectors = selector.split('/'); 
 
var properties = property.split('/'); 
 
for(var i = 0; i<selectors.length; i++) { 
 
\t selectors[i] = selectors[i].split(','); 
 
\t for(var j = 0; j<selectors[i].length;j++) { 
 
\t \t if(i==0) 
 
\t \t \t selector_array1.push(selectors[i][j]) 
 
\t \t else 
 
\t \t \t selector_array2.push(selectors[i][j]) 
 
\t } 
 
} 
 
alert(selector_array1); 
 
alert(selector_array2); 
 
</script> 
 
</body> 
 
</html>

関連する問題