javascript - 函数和 if else 语句不起作用

标签 javascript arrays function loops

我只是在学习如何编码,我现在正在使用 CodeWars 练习基础知识。由于 CodeWars 允许您查看解决方案,因此我查看了一些指导,这很有帮助。我使用这个网站作为指导,但无法弄清楚为什么我的功能不起作用。它是用 javascript 编写的。它只输出 []。这是问题、代码和输出(按以下顺序):

问题

Write a method, that will get an integer array as parameter and will process every number from this array. Return a new array with processing every number of the input-array like this: If the number has an integer square root, take this, otherwise square the number. [4,3,9,7,2,1] -> [2,9,3,49,4,1]

代码

function squareOrSquareRoot(array) {

    var newValues = []; // new array for new values

    for (i = 0; i < array.length; i++){ // for loop to look through the values

        var initial = array[i]; // extracting one value from the array to evaluate
        var sqrt = Math.sqrt(initial); // finding the square root of initial
        if (Number.isInteger(sqrt) == 'true'){ // determining if sqrt is an integer 
                                            // and if so .....
            newValues.push[sqrt];
        } // .... adding sqrt to the newValues array
        else if (Number.isInteger(sqrt) == 'false') { // determining if sqrt is not 
                                                      // an integer
            newValues.push[initial*initial];  // then multiplying initial by itself 
                                           //and adding to newValues
        }
    }
    return newArray; // returning newValues onto the screen
}

输出

Expected: '[2, 9, 3, 49, 4, 1]', instead got: '[]'

Expected: '[10, 10201, 25, 25, 1, 1]', instead got: '[]'

Expected: '[1, 4, 9, 2, 25, 36]', instead got: '[]'

最佳答案

您的条件有缺陷。改变

Number.isInteger(sqrt) == 'true'

Number.isInteger(sqrt) == true

Number.isInteger 返回 bool 值而不是字符串。另外第二个 else if 是多余的,如果 isInteger 返回 false 则只执行 else 部分而不是再次检查。 最后,您需要返回 newValues 而不是 newArray。希望对您有所帮助。

关于javascript - 函数和 if else 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45265047/

相关文章:

Javascript HTML 包含重复结果包含在随机位置

javascript - 检查 "checkbox"类型的输入的值是否等于数组成员?

javascript - 删除元素时循环遍历数组

c - 将 char** 传递给函数,不会改变它的值,还是会改变?

javascript - 如何检索以 JSON 格式接收的数组数据

javascript - 动态地在左侧显示具有相同类的 div,在右侧显示下一个类等等?

arrays - Scala 二维数组按指定列排序

c++ - 在priority_queue中使用greater<char>()

c++ - C++将函数调用列表作为参数传递

Delphi:加载BASS DLL并播放MP3