计算其他数组中的特定单词

我正在尝试计算数组B的特定单词出现在数组A中的次数。

我尝试了下面的代码,但输出为0。我不明白,为什么它会在功能开始时记录我分配给变量的值,并且不运行“ for”循环。

let A = ['really','basically','After','a','quick','popular','really','Red','began','very'];
let B = ['really','very'];

let number = () => {
  let count = 0;
  for (let i=0; i < A.lengths; i++) {
    if (B.includes(A[i])) {
      return count++;
    }
  }
   return console.log(count);
 }

number();

我希望结果应该是3。

qq313987933 回答:计算其他数组中的特定单词

您需要

  • length作为数组大小的属性
  • 继续循环,不及早返回
  • 通过返回console.log的结果,mabye返回计数,得到undefined

一个好主意

  • 将两个数组作为函数的参数,
  • 进行const声明/初始化,因为此变量是常量,
  • 是对变量使用小写字母。

const number = (a,b) => {
        let count = 0;
        for (let i = 0; i < a.length; i++) {
            if (b.includes(a[i])) {
                count++;
            }
        }
        return count;
   };

let array1 = ['really','basically','After','a','quick','popular','really','Red','began','very'];
let array2 = ['really','very'];


console.log(number(array1,array2));

,

一个衬里=> A.filter(item => B.includes(item)).length;

,

您为什么这么做:return count++;

return的目的是使用给定的值突破功能。当您编写return count++;时,它会返回计数,然后再递增计数(实际上,它不会使您已经超出函数作用域的任何内容递增)。

return console.log(count)也不做任何事情-除了代码永远不会到达那里,除非在B上找不到单词,这将从console.log返回未定义的返回值。

执行此操作:

let number = () => {
  let count = 0;
  for (let i=0; i < A.length; i++) {
    if (B.includes(A[i])) {
      count++;
    }
  }
   console.log(count);
   return count;
 }
,

1- 长度->不是长度

2- includes 仅检查该值是否存在于该数组中,以便它返回true或false

3- return 语句终止函数的执行

据我所知,您正在计算A中B元素的出现

这是一种实现方式:

let A = ['really','very'];
let B = ['really','very'];

let number = () => {
  let count = 0;
  for (let i=0; i < B.length; i++) {
    for (let j=0; j < A.length; j++){
      if (B[i] === A[j]) count++;
    }
    console.log(count);
    count = 0;
  }
   
 }

number();

,

您还可以使用reducefilter之类的高阶函数来代替循环。

let A = ['really','very'];

let total = B.reduce(function(accumulator,currentValue){

    let founds = A.filter(function(value,index){
        return value == currentValue;
    }).length;

    return accumulator + founds;

},0);


console.log(total);

,

您可以添加另一个for语句来迭代B中的元素,然后检查[i]处的A是否等于[j]处的B。虽然可能不如其他答案有效。

 let A = ['really','very'];
 let B = ['really','very'];

    let number = () => {
        let count = 0;
        for (let i = 0; i < A.length; i++) {
            for(let j=0; j < B.length; j++){
                if (A[i] == B[j]){
                    count++
                }
            }
        }
        return console.log(count);
    }

    number();
本文链接:https://www.f2er.com/3158267.html

大家都在问