如果给定一个脚本,如:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test DOC</title>
<script type="text/javascript" src="../nt_scr/jq_1.9.js"></script>
<script type="text/javascript">
var mainObj = { 0: { "fruitName":"Lemon",
"fruitColor":"green",
"fruitTaste":"bad"},
1: { "fruitName":"Mango",
"fruitColor":"Yellow",
"fruitTaste":"Yammy"},
2: {
"fruitName":"Banana",
"fruitColor":"Yellow",
"fruitTaste":"Yammy"},
"skip_these":
{
"team1":"Liverpool",
"team2":"Manchester United"
}
}
var collect_data = $.parseJSON(JSON.stringify(mainObj)),
getFruitNames=[],getFruitColors=[], getFruitTastes=[];
$.each( collect_data,function(index,val){
//console.log(val); //Un-comment this console.log to see the contents of 'val'
//----->Here is the Challenge:,---------\
if(/*How do you SKIP if val is something like */ "val.team1" || "val.team2"){
getFruitNames.push(val.fruitName);
getFruitColors.push(val.fruitColor);
getFruitTastes.push(val.fruitTaste);
//This works well so long as we have not yet reached the "skip_these":
//Once there, it reports an error because there is no "skip_these".fruitName or "skip_these".fruitColor
}
console.log( getFruitNames[index])// Run a test out put :: NOTICE the "Undefined" in the Console. How to avoid that?
//To see well, Comment the previous console.log <<the one on top>>
})
</script>
</head>
<body>
</body>
</html>
我以前也这样做过,但不知怎么的,我的大脑现在一片空白。。。。任何建议都将不胜感激。(请使用jQuery
运行)
作为JQuery文档状态,
返回非false与for循环中的continue语句相同;它将立即跳到下一次迭代。
因此,按照您的示例,您可以使用以下方法跳过具有不需要属性的对象:
JavaScript
$.each( collect_data,function(index,val){
//console.log(val); //Un-comment this console.log to see the contents of 'val'
//----->Here is the Challenge:,---------\
if(val.team1 || val.team2){
return true;
}
getFruitNames.push(val.fruitName);
getFruitColors.push(val.fruitColor);
getFruitTastes.push(val.fruitTaste);
//This works well so long as we have not yet reached the "skip_these":
//Once there, it reports an error because there is no "skip_these".fruitName or "skip_these".fruitColor
console.log( getFruitNames[index])//No "Undefined"
})
https://plnkr.co/edit/9vOACIpnlWRtSWjmAm5x?p=preview
(不是jquery-vanilla)迭代属性并跳过特定的键:(没有测试语法,但应该可以)
var skipped = ['keySkipped'];
for (var someProperty in someObject) {
if (someObject.hasOwnProperty(someProperty) && skipped.indexOf(someObject[someProperty] === -1)) {
// do stuff
}
}
解释:迭代属性,如果属性确实包含在对象中,但不包含在skiped
中,则执行