Javascript 将每个for函数用作对象属性
我有这篇文章的有效地图Javascript 将每个for函数用作对象属性,javascript,Javascript,我有这篇文章的有效地图 var articleMap = { author: function (author) { if(author) { return author.length > 0; } }, title: function (title) { if (!title) { return title.length > 0; } }
var articleMap = {
author: function (author) {
if(author) {
return author.length > 0;
}
},
title: function (title) {
if (!title) {
return title.length > 0;
}
}
};
这是要验证的文章的示例
var article =
{
id: '1',
title: '«Title',
summary: 'Summary',
createdAt: new Date(2017, 3, 5, 8, 0),
author: 'John',
content: 'Content',
tags: ['tag1', 'tag2'],
picture: 'images/id_1.jpeg'
};
当我使用each forObject.keys时,它只使用第一个键。但是当我使用forEach时,一切都很好。此外,当文章中没有某些键时,我的代码必须正常工作(例如'content'
)。我该修什么
Object.keys(articleMap).every(function (item) {
alert(articleMap[item](article[item]));
});
您应该使用forEach
,而不是every
:
Object.keys(articleMap).forEach(function (item) {
alert(articleMap[item](article[item]));
});
仅供参考:
every()方法测试数组中的所有元素是否通过了所提供函数实现的测试
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
而另一方面:
forEach()方法为每个数组元素执行一次提供的函数
var a = ['a', 'b', 'c'];
a.forEach(function(element) {
console.log(element);
});
首先检查文档总是好的 这是因为您没有从错误的回调返回任何内容(未定义的
)。@georg这是正确的吗?如果(!title)返回title.length>0代码>表示没有sense@Vladislav是的,那个把小提琴看起来不错,“当我在文章中并没有一些钥匙的时候,它一定能用”——那个么你们预计会发生什么?是否应该忽略对象和验证映射中都不存在的属性?(即,空对象始终有效)