如何检查所有数组值都是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");
}
答案 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)
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");
}