我有以下代码:
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];
....
所以我最终会得到2个for循环(我认为),比如:
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 :(得分:3)
你仍然可以在没有斜杠的情况下使用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());
答案 1 :(得分:0)
为此,您需要使用String原型的split方法:
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));
希望它有所帮助;)不要犹豫提问;)
答案 2 :(得分:0)
以下是使用split()
和数组的方法。
<!DOCTYPE html>
<html>
<head>
<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++) {
selectors[i] = selectors[i].split(',');
for(var j = 0; j<selectors[i].length;j++) {
if(i==0)
selector_array1.push(selectors[i][j])
else
selector_array2.push(selectors[i][j])
}
}
alert(selector_array1);
alert(selector_array2);
</script>
</body>
</html>
&#13;