简体   繁体   中英

Javascript for/forEach through radio buttons

I have a question on how to for loop and forEach loop work. I have 3 code samples, 2 of them work but returning in forEach loop does not work, why ?

  1. Works

     const radioButtons = document.getElementsByName("option"); for (let i = 0; i < radioButtons.length; i++) { if (radioButtons[i].checked) { return radioButtons[i]; } } 
  2. Works

     const radioButtons = document.getElementsByName("option"); let selectedRadioButton; radioButtons.forEach(function(button) { if (button.checked) { selectedRadioButton = button; } }); return selectedRadioButton; 
  3. Does not work - returning in forEach

     const radioButtons = document.getElementsByName("option"); radioButtons.forEach(function(button) { if (button.checked) { return button; } }); 

This is because Array.prototype.forEach does not support break behavior. The purpose of the function is to visit each element in the array, unconditionally. The method you want is Array.prototype.filter or in newer browsers, Array.prototype.find

const radioButtons = document.getElementsByName("option");

const button = radioButtons.filter(function(button) {
    return button.checked;
})[0];

In modern browsers:

const radioButtons = document.getElementsByName("option");

const button = radioButtons.find(button => button.checked);

It is worth noting, as D. Simon points out in his/her answer, that the return statement inside of a callback causes the callback itself to return, not the iteration method. JavaScript does not support what is known as non-local-return.

Here are some live examples:

 (function() { 'use strict'; var values = [1, 2, 3, 4, 5, 6]; var three = values.filter(function(value) { return value === 3; })[0]; console.info(three); }()); 

 (function() { 'use strict'; const values = [1, 2, 3, 4, 5, 6]; const three = values.find(value => value === 3); console.info(three); }()); 

第三个示例中的return语句将值返回到forEach语句内的匿名函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM