[英]What's wrong with this function? Doesn't return what I specified
The function needs to check if an array has numbers and return the first and the last number. 该函数需要检查数组是否包含数字,并返回第一个和最后一个数字。 If an array is empty - it should return an array with two zeros [0,0], if the first or last element in an array are not numbers - it should also return two zeros.
如果数组为空,则应返回两个零[0,0]的数组,如果数组的第一个或最后一个元素不是数字,则还应返回两个零。 I completed a function, but can't get it to work.
我完成了一个功能,但无法正常工作。
Completed a function. 完成功能。
function checkArrEl(arr) {
let result = [];
if ((arr.length == 0 ) || (typeof arr[0] || typeof arr[arr.length-1] !== 'number')) {
result = [0,0];
} else result.push(arr.shift(), arr.pop())
return result;
}
console.log(checkArrEl(['a',1,2,3,4,'b']));
console.log(checkArrEl([]))
console.log(checkArrEl([1,2,3,4,5]));
I'm assuming that expect (typeof arr[0] || typeof arr[arr.length-1] !== 'number')
to return true if either the first of last element of the array are not of type number
. 我假设如果数组的最后一个元素的第一个不是
number
类型,则期望(typeof arr[0] || typeof arr[arr.length-1] !== 'number')
返回true。
The first typeof
has no comparison operator paired with it. 第一个
typeof
没有与之配对的比较运算符。 In the case of arr=['a',1,2,3,4,'b']
, your expression is evaluating to 'string' || false
在
arr=['a',1,2,3,4,'b']
,您的表达式的计算结果为'string' || false
'string' || false
, which evaluates truthy every time. 'string' || false
,每次都会评估真实性。
Give the first typeof
a comparison operator so that your logic evaluates properly. 给第一
typeof
比较运算,这样你的逻辑计算正确。 The following if statement might work better for you. 以下if语句可能更适合您。
if ((arr.length == 0 ) || (typeof arr[0] != 'number' || typeof arr[arr.length-1] != 'number'))
The console now logs: 控制台现在记录:
[0, 0]
[0, 0]
[1, 5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.