如何检查数组值是否具有文件格式

时间:2019-08-15 17:39:41

标签: javascript

如何检查所有数组值都是HTML文件?如果数组不是完全以.html结尾的字符串,我想显示一条alert消息并停止它。我该怎么办?

https://jsfiddle.net/p57cjk81/2/

var arr = ["power.html", "sugar.html", "time.html", "kavi.html", "images.html"];
//var arr=["power.txt", "sugar.html", "time.html", "kavi.html", "images.html"];

var flag = true;

for (var i = 0; i <= arr.length; i++) {

  if (arr[i].split(.) == ".html"){
    flag = true;
  } else {
    flag = false;
  }

}

if (flag) {
  alert("Yes all the file have html");
} else {
  alert("All file are not html");  
}

3 个答案:

答案 0 :(得分:2)

您可以使用Array#every和一个正则表达式,该正则表达式使用.html行尾锚点来匹配某些内容以$结尾的字符串:

const arr = ["power.html", "sugar.html", "time.html", "kavi.html", "images.html"];

console.log(arr.every(e => /.+\.html$/.test(e)));

答案 1 :(得分:1)

尝试Array#some

const allHtml = (arr) => 
  !arr.some(
    f => { let parts = f.split("."); return parts.length!=2 || parts[1] !== "html"}
  );

let arr1=["power.html","sugar.html","time.html","kavi.html","images.html"];
let arr2=["power.html","sugar.jpg","time.html","kavi.html","images.html"];

console.log(
  allHtml(arr1),   
  allHtml(arr2)
);
  
// suggested usage:

var msg = allHtml(arr1) ? "Yes":"Not";
msg += " all the files have html extension in array";
alert(msg);

答案 2 :(得分:0)

类似这样的东西

var arr=["power.html","sugar.html","time.html","kavi.html","images.html"];

if(arr.every(e => /\.html$/.test(e))){
  alert("Yes all the file have html");
}
else{
  alert("All file are not html");
}