sko*_*jic 6 javascript jquery swap
我有一个字符串,其中以空格分隔的唯一数字如下:
"2 4 13 14 28 33"
Run Code Online (Sandbox Code Playgroud)
需要一种快速有效的方式来切换它们的形式:
switchNumbers(2, 28)
// result: "28 4 13 14 2 33"
Run Code Online (Sandbox Code Playgroud)
我可以分割字符串并搜索值,但这听起来很无聊.有什么好主意吗?
Tus*_*har 10
您可以利用array功能而不是strings.
请参阅代码中的内联注释:
var str = "2 4 13 14 28 33";
// Don't use `switch` as name
function switchNumbers(a, b) {
var arr = str.split(' ');
// Convert string to array
// Get the index of both the elements
var firstIndex = arr.indexOf(a.toString());
var secondIndex = arr.indexOf(b.toString());
// Change the position of both elements
arr[firstIndex] = b;
arr[secondIndex] = a;
// Return swapped string
return arr.join(' ');
}
alert(switchNumbers(2, 28));
Run Code Online (Sandbox Code Playgroud)
还尝试:
var numbers = "2 4 13 14 28 33";
function switchNum(from, to){
return numbers.replace(/\d+/g, function(num){
return num == from ? to : num == to ? from : num
})
}
alert(switchNum(2, 28)) //result: "28 4 13 14 2 33"Run Code Online (Sandbox Code Playgroud)
注意:不要使用switch函数名,switch是JavaScript的语句.
我无法判断这是否无聊但至少它不是分裂和循环:)
function switchNumbers(str, x, y) {
var regexp = new RegExp('\\b(' + x + '|' + y + ')\\b', 'g'); // /\b(x|y)\b/g
return str.replace(regexp, function(match) { return match == x ? y : x; });
}
var s = "2 4 13 14 28 33";
document.write('<pre>' + switchNumbers(s, 2, 28) + '</pre>');Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |