如何检测数组是否包含特定长度的任何值

时间:2019-03-10 23:38:18

标签: javascript arrays

我有一个如下数组:

var array = ['Bob','F', 'Nichols'];

我想检测此数组是否包含任何单个字符长的值。换句话说,我想知道此人的名字中是否有姓名缩写。

var array = ['Bob','F', 'Nichols']; //true
var array = ['B','Freddy', 'Nichols']; //true
var array = ['Bob','Freddy', 'N']; //true
var array = ['B','F', 'N']; //true
var array = ['B','F', 'N']; //true
var array = ['Bob','Freddy', 'Nichols']; //false

if (anyInitials(array)) {
    console.log("there are initials");
} else {
    console.log("there are no initials");
}

function anyInitials(a) {
    var arrayLength = a.length;
    var initial = 'no';
        for (var i = 0; i < arrayLength; i++) {
            if (a[i].length == 1){
                initial = 'yes';
            }
        }
    return initial;
}

2 个答案:

答案 0 :(得分:3)

您可以使用函数en

--locale

<?php

  header("Content-Type: application/octet-stream");
  header("Access-Control-Allow-Origin: *");

    $json = "";
    $file = "";
    $validation = true;

    if(!isset($_POST["file"])){
      $file = "";
      $validation = false;
      exit;
    }else{
      if(strcmp($_POST["file"], "tac") === 0){
        $file = $_POST["file"] .".pdf";
        $validation = true;
      }else{
        $validation = false;
        exit;
      }
    }

    if($validation){
      $result = openTAC($file);
    }else{
      $result = array("STATUS" => 'VF');
      echo json_encode($result);
    }

    function openTAC($file){

      if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header("Content-Type: application/force-download");
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        return array("STATUS" => 'OK');
      }else{
        header('Content-Type: text/json');
        return array("STATUS" => 'ERROR');
      }
    }

?>

答案 1 :(得分:0)

您可以使用一个简单的.forEach()循环,如下所示。这将遍历数组,如果长度为1,则将isInitial设置为true。

var array = ['Bob', 'F', 'Nichols'];

function anyInitials(a) {
  var isInitial = false;
  a.forEach(e => {
    if (e.length == 1) {
      isInitial =  true;
    }
  });
  
  return isInitial;
}

console.log(anyInitials(array));

您还可以如下使用.some()。如果数组中的任何元素的长度为1,则返回true。

var array = ['Bob', 'F', 'Nichols'];

function anyInitials(a) {
  return array.some(e => e.length == 1); 
}

console.log(anyInitials(array));