简体   繁体   English

此功能有什么问题? 不返回我指定的内容

[英]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.

相关问题 删除功能无法正常工作。 怎么了? - Delete function doesn't work properly. What's wrong? 我为自动化 web 组件创建而创建的 Javascript function 不起作用。 怎么了? - The Javascript function i created to automate web component creation doesn't work. What's wrong? Nodemailer不起作用,怎么了? - Nodemailer doesn't work, what's wrong? 我的脚本有什么问题? 它不返回带有“ if语句”的消息 - What is wrong with my script? It doesn't return a message with the “if statement” 将代码移至函数中。 现在不起作用。 怎么了? - Moved code into a function. Now doesn't work. What's wrong? 我的代码有什么问题? (第二个on(单击)功能不起作用) - What's wrong with my code? (second on(Click) function doesn't work) 我的代码中的“ animate()”函数不起作用,但“ css()”却起作用。 怎么了? - the 'animate()' function my code doesn't work but 'css()' does. what's wrong? 如果不希望返回任何内容,我应该在 https 可调用 function 中返回什么 - What should I return in an https callable function if it doesn't expect to return nothing JS有什么问题(在Mozilla中不起作用)? - What's wrong with JS (doesn't work in Mozilla)? 这个函数有什么问题(testFunction) - what's wrong with this function (the testFunction)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM