Logic judgment of every and some methods in JS ECMAScript 5

Source: Internet
Author: User

Two new logical operations on array elements in ECMA Script 5 some, every

Array.some (function (item) {});

Array.every (function (item) {});

The Every method means that when each element of the array returns true in the decision function, the final result is true, which is equivalent to the logical operator &&

Some when one of them returns true, the final result is true, equivalent to the logical operator | |.

Take the following example to illustrate:

        var items = [1, 2, 3, 4, 5];        var res = items.every (function (item) {            return item > 3;        });        Console.log (RES); False        items = [' A ', 2, 3, 4, 5];        res = Items.every (item) {            return!isnan (item),//Check for Value        }),//check whether each element is a digital        console.log (RES); /false        items = [' A ', 2, 3, 4, 5];        res = items.some (function (item) {            return!isnan (item);//Check whether it is a value        });        Console.log (RES); True    

  

Logical OR, of course, the logic and operation may encounter the case of an empty array, so according to the mathematical Convention, when the array is empty, some directly returns false, every directly returns True,

So when designing to a feature business, you need to be aware of this, and it's best to add a qualification to ensure that the array is not empty and that the code is intended to be read more clearly.

At the same time, it is understood from the specification that, as with logic and similarity, when one of the judgments returns false, the entire calculation stops directly, returning the final result false to improve efficiency. So please do not add other business logic or execute code in the decision function, if required, use map instead.

Logic judgment of every and some methods in JS ECMAScript 5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.