为什么slice(0,-1)不删除数组上的一个数字

时间:2019-04-01 15:24:43

标签: javascript arrays slice

我无法删除字符串中的最后一个数字。我尝试.pop,但如果我有[“ 12”,“ +”,“ 12”],他将弹出12我只需要一个。

quene.slice(0,-1)

enter image description here 我按CE键但不起作用 enter image description here

1 个答案:

答案 0 :(得分:1)

您需要先检查字符串的长度,然后根据该长度执行其余操作。

// check if last element length is more than 1
if(queue[queue.length - 1].length > 1){
  // remove last character and update string
  queue[queue.length - 1] = queue[queue.length - 1].slice(1, -1);
} else {
  // else remove the last element
  queue.pop();
}

或弹出最后一个元素,检查字符串的长度是否大于1,然后删除最后一个字符并压入数组。

// pop last element from the array
let last = quene.pop();

// check if element length is more than 1
if(last.length > 1){
  // remove last character from string and push to the array again
  queue.push(last.slice(1, -1))
}