从数组元素js返回一个移位元素

时间:2017-03-13 08:07:24

标签: javascript arrays if-statement shift

我需要按姓名返回下一个人。我尝试了其他版本,但有一次它返回了一个数字而不是字符串。道歉,现在是新的,但有一天会很棒。

 function nowServing(){
  if (katzDeli.length > 0) {
      return `Currently serving ${katzDeli.shift()}`;
        } else {
    return `There is nobody waiting to be served!`;
  }
  }

以上是跳过"如果"并执行" else。"如果数组为空,我需要它返回else字符串。 -update- 它会引发以下错误:  deli nowServing返回有关其所服务人员的公告,并改变该行:

  Error: Expected 'There is nobody waiting to be served!' to equal 'Currently serving Steven.'                                                   
  + expected - actual                                                                                                                            

  -There is nobody waiting to be served!                                                                                                         
  +Currently serving Steven.       

它位于我正在使用的课程的IDE中。所以我没有输入数组的值。当它读到(错误)时,它表示该行中没有任何人。另外,除此之外,我怎样才能避免掉线?每当我问一个问题时,我似乎都会得到一个。 感谢

2 个答案:

答案 0 :(得分:0)

当我尝试代码时,它运行正常:

function nowServing(){
  if (katzDeli.length > 0) {
    return `Currently serving ${katzDeli.shift()}`;
  } else {
    return `There is nobody waiting to be served!`;
  }
}

var katzDeli = ['foo', 'bar'];
console.log(nowServing()) // Currently serving foo
console.log(nowServing()) // Currently serving bar
console.log(nowServing()) // There is nobody waiting to be served!
console.log(nowServing()) // There is nobody waiting to be served!

如果您确实更新了问题,我也会更新答案。

答案 1 :(得分:-1)

我还有另一个建议。如果没有剩余元素,Array.prototype.shift()将返回undefined。

function nowServing() {
    var customer = katzDeli.shift();
    return `Currently serving ${customer ? customer : "nobody" }`;
}