Javascript 对象比较速记

Javascript 对象比较速记,javascript,Javascript,在这个对象中,有没有一种方法可以编写仍然保持对象样式的短代码?注意有时可能会有一组3,4,5,6,7个问题,代码是8个问题 我宁愿不使用数组解决方案,因为我有大量的对象集合 if(item[index].check=="agree") { if(item[index+1].check=="yes" &&item[index+2].check=="yes" &&item[index+3].check=="yes"

在这个对象中,有没有一种方法可以编写仍然保持对象样式的短代码?注意有时可能会有一组3,4,5,6,7个问题,代码是8个问题

我宁愿不使用数组解决方案,因为我有大量的对象集合

if(item[index].check=="agree") {
    if(item[index+1].check=="yes"
        &&item[index+2].check=="yes"
        &&item[index+3].check=="yes"
        &&item[index+4].check=="yes"
        &&item[index+5].check=="yes"
        &&item[index+6].check=="yes"
        &&item[index+7].check=="no"){
    ...
    totalqns=8
    }
}

您所拥有的似乎很好,但这里有一个略短的方法,使用映射和循环

var map = ["yes", "yes", "yes", "yes", "yes", "yes", "yes", "no"];
var all = item.every(function(key, index) {
    return key.check === map[index];
});

if ( all ) // do stuff

我可以这么说。您可以这样做:

var bool = true;
for (var i = 1; i <= 6; i++) {
  if (item[index+i] !== 'yes') {
    bool = false;
    break;
  }
}
if (bool && item[index+7] !== 'no') {
  bool = false;
}
var bool=true;
对于(var i=1;i,因为它是一个类似字符串的数组,我们可以使用
slice
join

var item = ["foo", "agree", "yes", "yes", "yes", "yes", "yes", "yes", "no", "bar"],
    index = 1;
if (Array.prototype.slice.call(item, index + 1, index + 7 + 1).join('') === 'yesyesyesyesyesyesno') {
    // pass
}
请考虑,如果您有
“yes”
“no”
以外的内容,则此操作可能会失败,例如,如果存在
“yesyesyes”
等值,则您无法通过这种方式区分
“yes”+“yes”
“yes”
“yes>“yes”
“yes”+“yes”


但是,如果要比较阵列,您有很多选择

mousetrap:do{//可以使用带标签的`if(true)`而不是带标签的`do..while(false)`
变量i,expect=[“是”、“是”、“是”、“是”、“是”、“是”、“是”、“否”];
对于(i=0;i<7;++i)
如果(项目[index+i+1]!==预期[i])
断开捕鼠器;//但不确定'if'中是否支持跨浏览器'break'
//通过
}while(假);


也不确定跨浏览器
foo:{expr;break foo;}
支持,
do..while
不应该抛出任何错误。

可能是a,但最后一个属性(在示例
项[index+7]
中)必须是“否”。示例代码检查所有属性是否都是“是”.请记住,它应该查找数组的
check
属性。(这个问题非常不清楚)你为什么要做
Array.prototype.slice.call
?@torazaburo没有假设
item
是一个数组,也没有假设
item.slice
存在,但是你刚刚定义了
item
,它非常像一个数组。@torazaburo OP没有定义
item
,我的定义只是为了示例,不能假设OP的
item的定义是相同的。虽然“如果您想比较数组,有很多选项”,但您选择了一种特别不清楚且非惯用的方法。标记为break和
do…while(false)
mousetrap: do { // could use labelled `if (true)` instead of labelled `do..while (false)`
    var i, expect = ["yes", "yes", "yes", "yes", "yes", "yes", "no"];
    for (i = 0; i < 7; ++i)
        if (item[index + i + 1] !== expect[i])
            break mousetrap; // but not sure of cross-browser `break` support in `if`s
    // pass
} while (false);