我想创建一个接受数组的函数。如果数组为空(或 === 0(,我想返回一个字符串。如果数组不为空,我想返回一个不同的字符串 + 删除 + 返回数组的第一个元素。我该如何实现此目的?
样本
> function(ary) {
> if (ary.length === 0) {
>-return string-
>}
>else {return other string + ary.shift[0]}
>}
下面是
您的代码,其中包含一个shift
更正:
function check(ary) {
if (ary.length === 0) {
return "empty";
} else {
return "First was the " + ary.shift()
}
}
console.log( check([]) );
console.log( check(['word', 'chaos', 'light']) );
shift
是一个不带参数的函数。应该这样称呼:
function(ary) {
if (ary.length === 0) {
return "string";
}
else {
return "other string" + ary.shift();
}
}
请注意,可以删除else
。只需 return 语句就足够了,因为如果 ary
的长度为 0,则永远不会到达 if
之后的代码(因为if
体内的return
(,因此之后的代码可以由 else
解开包装。喜欢这个:
function(ary) {
if (ary.length === 0) // remove the braces as well since the `if` body is just one statement
return "string";
return "other string" + ary.shift(); // if `if`'s test is true this line will never be reached
}