抱歉,如果这没有意义。我对此非常非常陌生。
我正在尝试解决返回数组的第一个和最后一个值的问题。 我觉得我已经掌握了这段代码的基础。 例如:
function getFirstAndLast(array) {
return [array.shift(), array.pop()]
}
let newArray = []
newArray = getFirstAndLast([5, 10])
控制台将打印:[5, 10]
但是,当仅给出 1 个参数时,控制台将返回该值且未定义。 例如:
function getFirstAndLast(array) {
return [array.shift(), array.pop()]
}
let newArray = []
newArray = getFirstAndLast([5])
控制台现在将打印:[5,未定义]
问题是如何更改代码以仅返回没有未定义的单个值,但如果给定 2 个或更多参数,仍然保留提取第一个和最后一个数组值的能力。
如果这没有意义或者我错误地调用了错误的内容,再次抱歉。 谢谢
最佳答案
只需使用长度,如果length
为1,则返回相同的数字,例如:
function getFirstAndLast(array) {
return (array.length === 1) ? [array[0], array[0]] : [array.shift(), array.pop()];
}
console.log(getFirstAndLast([5]));
console.log(getFirstAndLast([5,10]));
console.log(getFirstAndLast([5,10,15]));
更好地检查空值,例如:
function getFirstAndLast(array) {
const lenArr = array.length;
if (lenArr === 0) {
return [];
} else {
return (lenArr === 1) ? [array[0], array[0]] : [array.shift(), array.pop()];
}
}
console.log(getFirstAndLast([]));
console.log(getFirstAndLast([5]));
console.log(getFirstAndLast([5, 10]));
console.log(getFirstAndLast([5, 10, 15]));
引用:
关于javascript - 如果搜索第一个和最后一个数组并且给定参数只有 1 个值,如何在函数中仅返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73052268/