簡體   English   中英

JS函數計算數組中的奇數和負數

[英]JS function to count odd numbers and negatives in array

我目前正在嘗試編寫一個JS函數,該函數需要多個參數來對“數組”中的奇數和負數進行計數或計數。 我把數組放在引號中,因為函數實際上接受了參數。

我想使用一個for循環來獲取賠率和負數,但是我的代碼無法正常工作。

function arrayAnalyzer() {

var myArray = Array.prototype.slice.call(arguments)

var counter = {
  odds : 0,
  negatives : 0,
  avg : 0,
  median : 0
}

  for(var i = 0; i < myArray.length; i++) {

    if(myArray{i] % 2 === 1) {
       counter.odds++ }

    if(myArray[i] < 0) {
       counter.negatives++ }
    }  

return counter
}

 arrayAnalyzer(7, -3, 0, 12, 44, -5, 3);

我在網上發現該代碼有效,但是如果可能的話,我想使用一個for循環。

myArray.forEach(function(num){
    if (Math.abs(num) % 2 === 1) counter.odds++
    if (num < 0) counter.negatives++
})

似乎在您的第一個if語句中使用了輕微的語法修復:

function arrayAnalyzer() {

var myArray = Array.prototype.slice.call(arguments)

var counter = {
  odds : 0,
  negatives : 0,
  avg : 0,
  median : 0
}

  for(var i = 0; i < myArray.length; i++) {

    if(myArray[i] % 2 === 1) {
       counter.odds++ }

    if(myArray[i] < 0) {
       counter.negatives++ }
    }  

return counter
}

工作JSBIN: https ://jsbin.com/yokawu/edit js,console

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM