我正在尝试编写一个带有3个参数的函数,然后在删除给定索引后返回一个字符串。这是我的代码:
var name = {};
function strCut(arg1, arg2, arg3){
if(arg1 === 'Jordi')
arg1.splice(0, 1) && arg1.splice(4,1)
return arg1
}
strCut('Jordi', 0, 4)
//我正在尝试拼接“ J”和“ i” 返回name = ord的数组
答案 0 :(得分:2)
尝试此功能:
function strCut(arg1, arg2, arg3) {
if (arg1 === 'Jordi') {
var temp = arg1.split("");
delete temp[arg2]
delete temp[arg3]
}
// return temp.join("") if you want to return a string.
return temp.join("").split("");
}
console.log(strCut('Jordi', 0, 4))
答案 1 :(得分:1)
String
而不是Array
?如果您需要将String
转换为Array
,则可以使用str.split('');
arg2
和arg3
而不是常数0和4?&&
不能连接字符串或数组,则应该对字符串使用+
运算符,对数组使用.concat
或... (spread operator)
。var name = {}; function strCut(str, firstIndex, secondIndex){ var largerIndex = Math.max(firstIndex, secondIndex); var smallerIndex = Math.min(firstIndex, secondIndex); str = str.slice(0, largerIndex) + str.slice(largerIndex + 1); //Removing the larger index str = str.slice(0, smallerIndex) + str.slice(smallerIndex + 1); //Removing the smaller index return str; } strCut('Jordi', 0, 4);
var name = {}; function strCut(str, firstIndex, secondIndex){ var largerIndex = Math.max(firstIndex, secondIndex); var smallerIndex = Math.min(firstIndex, secondIndex); str = str.slice(0, largerIndex).concat(str.slice(largerIndex + 1)); //Removing the larger index str = str.slice(0, smallerIndex).concat(str.slice(smallerIndex + 1)); //Removing the smaller index return str; } strCut('Jordi'.split(''), 0, 4); //The string gets passed as an array this way