0

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

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);
4

3 回答 3

1

首先,我注意到您正在使用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);

于 2021-02-28T21:01:27.643 回答
0

只需删除语句后的分号即可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数组。

(我也想你想要 aconsole.log在最后而不是print?)

于 2021-02-28T20:50:51.093 回答
0

你为什么不使用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 注意到的那样,您的代码是错误的。

于 2021-02-28T20:58:34.180 回答