Javascript高阶函数:将回调函数传递给过滤器不起作用

时间:2016-09-09 16:36:35

标签: javascript functional-programming higher-order-functions

我试图通过返回true的数组过滤掉数组的值。我有一个名为noRepeat的函数,如果给定年份没有重复数字,则返回true,否则返回false。

我有另一个名为no_repeats(yearStart,yearEnd)的函数,它从头到尾创建一个年数组。我希望在那些没有数字重复的年份过滤掉这个数组,我不确定为什么它不起作用。有任何想法吗?我也包含了问题陈述,在代码中我展示了我的输出与应该是什么。

 Write a function, `no_repeats(year_start, year_end)`, which takes a
 range of years and outputs those years which do not have any
 repeated digits.

 You should probably write a helper function, `no_repeat?(year)` which
 returns true/false if a single year doesn't have a repeat.

 Difficulty: 1/5

function no_repeats(yearStart, yearEnd){
    //call no repeats on each year from yearStart to yearEnd and return an array of years that have noRepeat(year) === true
    var yearRangeArr = [];
    var returnArr = [];
    while (yearEnd >= yearStart){
        yearRangeArr.push(yearEnd);
        yearEnd-=1;
    }
    yearRangeArr.filter(function(year){
        return noRepeat(year);
    });
    return yearRangeArr;


}

function noRepeat(year){ //works
    //create an array pushing each year's digits
    // if arr.indexOf(digit) > -1 then the digit already exists, so return false
    // else append the digit, and if no digit repeats, return true
    year = year.toString();
    var repeatArr = [];
    for (i = 0; i < year.length; i++){
        //console.log(repeatArr);
        if (repeatArr.indexOf(year[i]) > -1){ //if the digit exists in arr
            return false;
        }
        else{
            repeatArr.push(year[i]);
        }
    }
    return true;
}

//var testArr= [1,2,3,4,2];
//console.log(testArr.indexOf(10));

//console.log(noRepeat(1234));
console.log(no_repeats(1234, 1234)); //== [1234]); 
console.log(no_repeats(1123, 1123)); // == []); ANSWER SHOULD BE [], I'M GETTING [1123].

1 个答案:

答案 0 :(得分:0)

filter()返回新值,它不会改变原始对象。您必须将返回值分配给变量:

yearRangeArr = yearRangeArr.filter(function(year){
    return noRepeat(year);
});