简体   繁体   English

javascript通过“ for”和“ ForEach”遍历数组

[英]javascript loop through array with “for” and “ForEach”

i'm trying to create a function that take an array as an argument, and return "true" only if all the items inside the array are the same . 我试图创建一个将数组作为参数的函数,并且仅当数组中的所有项目都相同时才返回“ true”。
i try to use for loop and i try to use forEeach loop 我尝试使用for循环 ,我尝试使用forEeach循环
the first one work great. 第一个作品很棒。
the second one not!. 第二个没有!
why? 为什么?
this my first code: 这是我的第一个代码:

function isUniform(ary) {
    var first = ary[0];
    for (i = 0; i < ary.length; i++) {
        if (first !== ary[i]) {
            return false;
        }
    }
        return true;
}
console.log(isUniform([1, 2, 1]));

this my second one: 这是我的第二个:

function isUniform(ary) {
    var first = ary[0];
    ary.forEach(function(element) {
        if (first !== element) {
            return false;
        }
    });
    return true;

}
 console.log(isUniform([1, 2, 1]));

The "inner" return in your second example is a return from the function passed to forEach . 在第二个示例中,“内部” return是传递给forEach的函数的返回。 It does not cause an immediate return from the isUniform function. 不会导致从立即返回isUniform功能。 Instead, this little anonymous function you passed to forEach runs happily to completion for every single element of your array. 取而代之的是,您传递给forEach这个小匿名函数可以为数组的每个元素愉快地运行到完成。

After it finishes running through all of the elements, your isUniform function then simply returns true. 完成所有元素的运行后, isUniform函数将简单地返回true。

By returning true you are returning true to the forEach function callback while you're for loop returns true to the function. 通过返回true,您将true返回到forEach函数回调,而您的for循环将true返回给该函数。 Your forEach requires a reference object when executing a callback if you want to use your current approach. 如果要使用当前方法,则forEach在执行回调时需要参考对象。 That is how it is different from your for loop. 那就是它与for循环的不同之处。

 function isUniform(ary) { var first = ary[0]; val = true; ary.forEach(element => { if (first !== element) { val = false; } }); return val; } console.log(isUniform([1, 1, 1])); console.log(isUniform([1, 2, 1])); 

There is already an every function you can take advantage of. 您已经可以利用每个功能。

 arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; arr2 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; console.log(arr1.every((a, _, aa) => aa[0] === a)); console.log(arr2.every((a, _, aa) => aa[0] === a)); 

You can't break from a forEach. 您无法脱离forEach。

Try this one. 试试这个。 You can do it with the flag. 您可以使用标志来实现。

var falg = false; var falg = false;

function isUniform(ary) { 函数isUniform(ary){

var first = ary[0];

ary.forEach(function(element) {

    if (first !== element) {

        falg = true;

        return false;

    }

});

if(falg)

    return false

return true;

} }

console.log(isUniform([1, 2, 1])); console.log(isUniform([1,2,1]));

The how part has been addressed in @Arrow's post already, if you work with forEach , it does not care about the return values, you have to accumulate the result yourself (also, there is no 'normal' way of breaking out from the loop, though you could throw an exception if you really want to). @Arrow的帖子中已经解决了部分问题,如果您使用forEach ,它不关心返回值,那么您必须自己累加结果(而且,没有“正常”的方法可以退出循环) ,但如果您确实愿意,可以抛出异常)。

For the 'why' part: because of definition. 对于“为什么”部分:由于定义。 forEach does not care about return values and runs the passed function for all elements, unconditionally. forEach不在乎返回值,而是无条件地为所有元素运行传递的函数。

A simplified implementation of forEach is the following: forEach的简化实现如下:

Array.prototype.myForEach=function(callback){ // or callback,diz
  for(var i=0;i<this.length;t++)
    callback(this[i],i,this);                 // or callback.call(diz,this[i],i,this);
}

The result of callback is completely ignored. callback的结果被完全忽略。 (Commented parts add support for the optional context-argument) (注释部分增加了对可选上下文参数的支持)

A 'more official' polyfill does some extra checks, but it is not complicated either: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill “更正式”的polyfill会做一些额外的检查,但也并不复杂: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill

can you try this, change the var element for x, and use lambdas 您可以尝试一下吗,将var元素更改为x,并使用lambdas吗?

    function isUniform(ary) {
     var first = ary[0];
     ary.forEach((x) => {
         if(first !== x){
             return false;
         }
     });
     return true;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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