标准数组更改为关联数组中断JS函数

时间:2015-06-08 14:25:26

标签: javascript arrays

这是我用来检查输入的脚本,如果它们与数组中的值相同并且是否有任何重复

 echo '<input class="champion" type="text" list="champions" placeholder="Champion '.$i.'" name="champno[]" required autofocus><br/>
                        <datalist id="champions"></datalist>';
var config = {
              fillAll: true
            };

            document.forms["second_form"].oninput = function(e) {
              var champion = this["champno[]"];

              //Force into array
              if (champion[0] === undefined)
                champion = [this["champno[]"]];

              var reached = {
                valid: 0,
                unique: 0
              };

              var inputs = [].map.call(champion, function(n) {
                return n.value
              }).filter(function(n) {
                return n.length
              });

              var valid = [].every.call(champion, function(n, i) {
                n.setCustomValidity("");
                if (config.fillAll) return (reached.valid = i, champions.indexOf(n.value) > -1);
                else return n.value ? (
                  reached.valid = i,
                  champions.indexOf(n.value) > -1
                ) : true;
              });

              var unique = inputs.slice(0).sort().every(function(n, i, a) {
                reached.unique = inputs.lastIndexOf(n);
                return n != a[i - 1];
              });

              //Check for valid champions
              if (!valid) {
                champion[reached.valid].setCustomValidity("This is not a valid champion, please correct this field and resubmit.")
              }

              //Check for duplicates
              if (!unique) {
                champion[reached.unique].setCustomValidity("This champion has already been entered.")
              }

              this.checkValidity();
            };

我改变了我的阵列:

var champions = [
            "Aatrox", "Ahri", "Akali"
        ];

对此:

var champions = {

    "Aatrox":["Blood Well","Dark Flight", "Blood Thirst / Blood Price", "Blades of Torment", "Massacre"],
    "Ahri":["Essence Theft","Orb of Deception", "Fox-Fire", "Charm", "Spirit Rush"],
    "Akali":["Twin Disciplines", "Mark of the Assassin", "Twilight Shroud", "Crescent Slash", "Shadow Dance"]
    };

错误地打破了脚本:&#39; champions.indexOf不是函数&#39;而且我不确定如何解决这个问题

1 个答案:

答案 0 :(得分:0)

.indexOf是Array原型的一部分,不可用于对象文字。如果你所做的只是检查密钥是否存在,你可以这样做:

if( champions[n.value] ) ...

或者:

champions.hasOwnProperty(n.value)