Home >Web Front-end >JS Tutorial >How to find odd elements in an array in javascript

How to find odd elements in an array in javascript

青灯夜游
青灯夜游Original
2022-02-17 18:37:595876browse

Method: 1. Use the for statement to traverse the array, and use the "a[i] % 2 != 0" statement in each loop to determine whether the array element is an odd number. If so, output it, if not, jump out. This loop is enough; 2. Use the filter() method to return the elements in the array that meet the "value % 2 != 0" condition.

How to find odd elements in an array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript method to find the odd number of an array:

Method 1: Use for loop

Implementation idea: Use the for statement to traverse the array, and determine whether the array element is an odd number in each loop. If so, output it. If not, jump out of the loop.

Implementation code:

var a = [2, 3, 4, 5, 6, 7, 8];
for (var i = 0; i < a.length; i++) {
	if (a[i] % 2 != 0) {
		console.log(a[i]);
	} else {
		continue;
	}
}

How to find odd elements in an array in javascript

Method 2: Using the filter() method

var a = [2,3,4,5,6,7,8];
function f (value) {
	if (value % 2 != 0) {
		return true;
	}else{
		 return false;
	}
}
var b = a.filter(f);
console.log(b);

How to find odd elements in an array in javascript

Description:

ilter() method can return elements in the array that meet specified conditions.

array.filter(function callbackfn(Value,index,array),thisValue)

function callbackfn(Value,index,array): A callback function, which cannot be omitted. It can accept up to three parameters:

  • value: current array The value of the element, which cannot be omitted.

  • index: The numeric index of the current array element.

  • array: The array object to which the current element belongs.

The return value is a new array containing all the values ​​for which the callback function returns true. If the callback function returns false for all elements of array , the length of the new array is 0.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to find odd elements in an array in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn