我需要编写一个循环遍历数字数组的函数,并返回奇数和数字。在它的数组中偶数。

时间:2017-08-29 16:23:31

标签: javascript arrays

我需要编写一个循环遍历数字数组的函数,然后返回奇数&在数组中偶数。

我不确定是否有更好的方法来做到这一点,而且我被卡住了。有没有办法返回两个语句?

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        // Other statements ...

        // Configure the application for OAuth based flow
        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
#if LIVE
            AllowInsecureHttp = false,
#else
            AllowInsecureHttp = true,
#endif
            RefreshTokenProvider = new ApplicationOAuthRefreshTokenProvider()
        };
        app.UseOAuthBearerTokens(oAuthOptions);
    }

4 个答案:

答案 0 :(得分:1)

一种清洁功能,可以将平均值与赔率分开。



function arrangeNums(array) {
  let odd = array.filter(i=>i%2!==0);
  let even = array.filter(i=>i%2===0);
  return {even:even,odd:odd};
}
console.log(arrangeNums([...Array(100).keys()]));




答案 1 :(得分:0)

返回数组而不是console.log应该工作



var myNums = [1, 2, 3, 4, 5, 6, 7, 9];

var evens = []; 
var odds = [];  

function oddsAndEvens(nums) {
	for(var i = 0; i < nums.length; i++){
      if(nums[i] % 2 === 0){
        evens.push(nums[i])
      }
      else if (!nums[i] % 2 === 0) {
		odds.push(nums[i])
      }
    }  
    
     // return array of values you want
     return [evens, odds] 
}
  
console.log(oddsAndEvens(myNums));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以使用一个对象作为结果,并为对象的键取一个数组来推送值。

&#13;
&#13;
function getGrouped(array) {
    return array.reduce(function (r, a) {
        r[['even', 'odd'][a % 2]].push(a);
        return r;
    }, { odd: [], even: [] });
}

var myNums = [1, 2, 3, 4, 5, 6, 7, 9];

console.log(getGrouped(myNums));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 3 :(得分:0)

当然你可以,只返回一个包含平均值和赔率的对象,

&#13;
&#13;
    function oddsAndEvens(nums) 
    {
      var evens = [];
      var odds = [];
      for(var i = 0; i < nums.length; i++){
          if(nums[i] % 2 === 0){
            evens.push(nums[i])
          }
          else if (!nums[i] % 2 === 0) {
    		    odds.push(nums[i])
          }
        }  
        return {"evens":evens,"odds":odds};   
    }
      
    var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
    result = oddsAndEvens(myNums);
    console.log(result.evens);
    console.log(result.odds);
&#13;
&#13;
&#13;