如何在 javascript 中使用 forEach 中的中断?

Ilj*_*lja 4 javascript reactjs babeljs

在 reactjs-babel 应用程序中,我尝试使用break时发生了奇怪的行为forEach

    var SomeElement = React.CreateClass({
        ... ,
        getMessageStatus: function getMessageStatus(message) {
            var states = this.state.messages_states;
            var status = undefined;
            states.forEach(function (messageEntity) {
                if (messageEntity.id == message.id && messageEntity.is_question == message.is_question) {
                    status = messageEntity.status;
                    break; // - this is not working 
                }
            });
            return status;
        },
        ...
        });
Run Code Online (Sandbox Code Playgroud)

breakCannot determine target for 'break'在 PhpStorm 和 Babel repl 中说它像repl: Unsyntactic break 如何正确使用 break 一样?

Tir*_*Rao 10

There is no in-built ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.

var BreakException= {};

try {
    [1,2,3].forEach(function(el) {
        if(el === 1) throw BreakException;
    });
} catch(e) {
    if (e!==BreakException) throw e;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.

Instead, use of Array#some:

[1,2,3].some(function(el) {
    return el === 1;
});
Run Code Online (Sandbox Code Playgroud)

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.


str*_*str 5

There is no need for forEach when you want to break on the first occurrence. Just use find() instead.

 status = states.find((messageEntity) => 
     messageEntity.id == message.id && messageEntity.is_question == message.is_question
 ).status;
Run Code Online (Sandbox Code Playgroud)