首页 > 解决方案 > 为什么 slice(0,-1) 不只删除数组上的一个数字

问题描述

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

quene.slice(0,-1)

在此处输入图像描述 我按 CE 但不工作 在此处输入图像描述

标签: javascriptarraysslice

解决方案


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

// 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))
}

推荐阅读