JavaScript:如何创建一个接收数字数组和 returns 仅包含正数的数组的函数?

JavaScript: How to create a function that receives an array of numbers and returns an array containing only the positive numbers?

这段代码有什么问题?我应该创建一个函数来接收一个数字数组和 returns 一个只包含正数的数组。如何修改?特别修改。不是另一个代码!

all = prompt("Give me an array of numbers seperated by ','");

var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
    var positive = [];

for(var i = 0; i < splitted.length; i++);{
    var el = splitted[i];
    if (el >= 0){
        positive.push(el);
    }
    
}
return positive;
}

var positive = returner(splitted);
print(positive);

for语句后面的分号去掉就好了:

all = prompt("Give me an array of numbers seperated by ','");

var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
    var positive = [];

for(var i = 0; i < splitted.length; i++){
    var el = splitted[i];
    if (el >= 0){
        positive.push(el);
    }
    
}
return positive;
}

var positive = returner(splitted);
console.log(positive);

实际上,对于那个分号,你“什么都不做”n 次,然后自己执行块,这无助于填充你的数组,因为 i 变量已经通过了最后一个数组的索引,因此 splitted[i] 结果为 undefined 而不是 >=0 因此没有任何内容被推送到 positive 数组。

(另外我想你想要一个 console.log 而不是 print?)

你为什么不使用 filter

var array = [3, -1, 0, 7, -71, 9, 10, -19];

const getpositiveNumbers = (array) => array.filter(value => value > 0);

var positives = getpositiveNumbers(array);

console.log(positives);

无论如何,正如@trincot 所注意到的,您的代码是错误的。

首先我注意到您正在使用 print 来检查您的输出 - 应该是 console.log()。 但你真正的错误是第 7 行 for 括号后面的分号。

这是一个有效的代码片段:

let all = prompt("Give me an array of numbers seperated by ','");

let splitted = all.split`,`.map(x => +x);
function returner(splitted) {
    let positive = [];

    for (let i = 0; i < splitted.length; i++) {
        const el = splitted[i];
        if (el >= 0) {
            positive.push(el);
        }
    }

    return positive;
}

var positive = returner(splitted);
console.log(positive);