从Javascript中的数组中删除多个索引

时间:2018-09-06 17:52:22

标签: javascript arrays splice

我正在尝试编写一个带有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的数组

2 个答案:

答案 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))

查看Join并拆分functions

答案 1 :(得分:1)

  • 我认为您是说String而不是Array?如果您需要将String转换为Array,则可以使用str.split('');
  • 我还认为您的函数应使用arg2arg3而不是常数0和4?
  • 如果要使用&&不能连接字符串或数组,则应该对字符串使用+运算符,对数组使用.concat... (spread operator)
  • / li>
  • 问题在于,当您删除一个索引时,另一个索引会减少一个,一种简单的解决方案是先删除较大的索引。
  • 如果它是字符串,这是您的代码:
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
相关问题