我会将其拆分为一个解析字符串的函数和一个执行 DOM 操作的函数。就像是:
function parseString (str, sep, eq) {
sep = sep || ';';
eq = eq || '=';
var result = {};
if(!str)
return result;
var pairs = str.split(sep);
for (var i = 0, len = pairs.length; i < len; i++) {
var pair = pairs[i].split(eq);
// Disregard if we don't have a key
if(!pair[0].length)
continue;
result[pair[0]] = pair[1];
}
return result;
}
function setValues(params) {
for(id in params)
$('#' + id).value(params[id]);
}
// Add values for ids as specified in myString
var myString = "key1=value1;key2=value2;key3=value3";
setValues(parseString(myString));
更新:
如果您知道代码将在现代 JS 引擎上运行,您可以使用Array.prototype.map
和Array.prototype.reduce
以获得更简洁的代码。这仅适用于符合 ES5 的引擎(即,不适用于 IE < 9)。
function parseString (str, sep, eq) {
sep = sep || ';';
eq = eq || '=';
if(!str)
return {};
function splitPair (pair) { return pair.split(eq) }
function addResult (result, pair) {
if(pair[0].length)
result[pair[0]] = pair[1];
return result;
}
return str.split(sep)
.map(splitPair)
.reduce(addResult, {});
}
使用示例parseString
:
console.log(parseString('key1=value1;key2=value2;key3=value3'));
{ key1: 'value1', key2: 'value2', key3: 'value3' }
console.log(parseString('=value1;key2=value2;key3=value3'));
{ key2: 'value2', key3: 'value3' }
console.log(parseString(';key1=value1;key2=value2;key3=value3'));
{ key1: 'value1', key2: 'value2', key3: 'value3' }
console.log(parseString('key1=value1;key2=value2;key3=value3;'));
{ key1: 'value1', key2: 'value2', key3: 'value3' }
console.log(parseString('key1=value1'));
{ key1: 'value1' }
console.log(parseString('key1='));
{ key1: '' }
console.log(parseString('key1'));
{ key1: undefined }
console.log(parseString(''));
{}
console.log(parseString());
{}