当我运行以下内容时:
var months = new Set(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
var array = words;
array = $.map(array, function(value){
return value.replace(/ /g, '');
});
const dates = {
days : [],
months : [],
years : [],
suffixes : []
}
for (const word of words) {
if (months.has(word)) {
dates.months.push(word);
} else if (+word < 32) {
dates.days.push(+word);
} else if (+word < 2200) {
dates.years.push(+word);
} else if (/\w+/.test(word)) {
dates.suffixes.push(word);
}
}
console.log(array);
console.log(dates);
输出不正确:
Object {days: Array(2), months: Array(0), years: Array(1), suffixes: Array(2)}
如果我跑:
var months = new Set(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
var words = ["27","-","28","August","663","CE"];
const dates = {
days : [],
months : [],
years : [],
suffixes : []
}
for (const word of words) {
if (months.has(word)) {
dates.months.push(word);
} else if (+word < 32) {
dates.days.push(+word);
} else if (+word < 2200) {
dates.years.push(+word);
} else if (/\w+/.test(word)) {
dates.suffixes.push(word);
}
}
console.log(dates);
输出正确:
Object {days: Array(2), months: Array(1), years: Array(1), suffixes: Array(1)}
答案 0 :(得分:3)
因为你在第一个代码中添加了一个空格,这是完全不必要的:
words[i] += " ";
原因
"january "
在数组(或Set)中找不到,因为它只包含:
"january"
答案 1 :(得分:0)
您好,您正在使用&#34;字&#34;数组偶数&#34;数组&#34;,它有空格。 这个demo给出了预期的结果:
var string = "27 - 28 August 663 CE";
var months = new Set(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
const dates = {
days : [],
months : [],
years : [],
suffixes : []
};
var array = words;
array = array.map(array, function(value){
return value.replace(/ /g, '');
});
console.log(array, 'array');
console.log(words);
for (word of array) {
if (months.has(word)) {
dates.months.push(word);
} else if (+word < 32) {
dates.days.push(+word);
} else if (+word < 2200) {
dates.years.push(+word);
} else if (/\w+/.test(word)) {
dates.suffixes.push(word);
}
}
console.log(dates);