0

In this function, variable midArc stores positive and negative numbers. How can these values be used to create two new arrays, one containing positive values and another one containing negative values?

function cosVal(){
    var val = [2,5,7,6,9];
    for(i=0; i<val.length; i++){
        var midArc = Math.cos(val[i]);
        alert(midArc); //displays 3 positive and 2 negative numbers 
    }   
}
4

2 回答 2

0

这是一个可能的解决方案:它将负数推送到一个数组,将正数(和零)推送到另一个数组。

function cosVal(){
    var aryNeg=[];
    var aryPos=[];
    var val = [2,5,7,6,9];
    for(i=0; i<val.length; i++){
        var midArc = Math.cos(val[i]);
        if(midArc<0){
            aryNeg.push(midArc);
        }else{
            aryPos.push(midArc);
        }
        alert(midArc); //displays 3 positive and 2 negative numbers 
    }   
}
于 2013-05-09T23:37:31.683 回答
0

只需检查数字是否大于或小于零:

function cosVal(){
    var val = [2,5,7,6,9], positives = [], negatives = [];
    for(i=0; i<val.length; i++){
        var midArc = Math.cos(val[i]);
        (midArc >= 0) ? positives.push(midArc) : negatives.push(midArc);
    }   
}
于 2013-05-09T23:38:39.923 回答