简体   繁体   中英

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. 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 .

The first typeof has no comparison operator paired with it. In the case of arr=['a',1,2,3,4,'b'] , your expression is evaluating to 'string' || false 'string' || false , which evaluates truthy every time.

Give the first typeof a comparison operator so that your logic evaluates properly. The following if statement might work better for you.

if ((arr.length == 0 ) || (typeof arr[0] != 'number' || typeof arr[arr.length-1] != 'number'))

The console now logs:

[0, 0]
[0, 0]
[1, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM